I want to stream audio buffers from JavaScript to my flask server, using socket.io. But the socket instance is 'undefined' when I want to use it from within the audio callback function.
In this code, my socket instance in the main thread is 'socket'. The function 'record' is called from the worker every time a new buffer is received from the microphone.
But the socket.emit always gives me:
Uncaught ReferenceError: socket is not definedrecord @ blob:http://localhost:7777/400a58bc-b64f-4c66-9bb1-65a28bf9bfba:39onmessage @ blob:http://localhost:7777/400a58bc-b64f-4c66-9bb1-65a28bf9bfba:15
How can I access the socket correctly from within the worker?
In the main thread, I have the socket object and the method that is called in postMessage from the web worker:
var socket = io.connect('http://' + document.domain + ':'+location.port);
socket.on('connect', function() {
socket.emit('my event', {data: 'I\'m connected!'});
});
...
function record(inputBuffer){
var buf = inputBuffer[0]
///////HERE THE socket CANNOT BE FOUND, WHY??
socket.emit('audio event',{data : buf})
}
In the web worker thread, postMessage calls the 'record' method:
this.onmessage = function(e){
switch(e.data.command){
case 'record':
/////HERE THE 'record' FUNCTION IS CALLED IN THE MAIN THREAD
record(e.data.buffer);
break;
}
};
...
(function(window){
var Recorder = function(source, cfg){
this.context = source.context;
if(!this.context.createScriptProcessor){
this.node = this.context.createJavaScriptNode(bufferLen, 2, 2);
} else {
this.node = this.context.createScriptProcessor(bufferLen, 2, 2);
}
var currCallback;
this.node.onaudioprocess = function(e){
////THIS IS THE CALLBACK FROM MICROPHONE HARDWARE
worker.postMessage({
command: 'record',
buffer: [
e.inputBuffer.getChannelData(0),
e.inputBuffer.getChannelData(1)
]
});
}
this.record = function(){
recording = true;
}
worker.onmessage = function(e){
var blob = e.data;
currCallback(blob);
}
window.Recorder = Recorder;
})(window);