Hi I found the way to send the audio data to server by MediaRecorder, but it is works only as a recorder but I need a stream. I mean it works only after the stop of MediaRecorder. But I need to send data while it available, sort of audio stream…
My code:
mediaRecorderAudio.addEventListener("dataavailable", (stream) => {
// Send stream data while mediaRecorderAudio is active
( async ()=>{
let blob = new Blob(stream.data, { type: "audio/ogg; codecs=opus" });
let buffer = await blob.arrayBuffer();
let data_to_send = new Uint8Array(buffer);
socket.emit('socket_audio',JSON.stringify(data_to_send))
});
});
mediaRecorderAudio.start(100);
If I starting and send to server just blobs, it is working while data availble. But with the coding of data to buffer – it not sends anything. I mean without async
function. Any ideas?
2
Answers
Solution to move async to the whole function in the callback:
When you define an anonymous function like this…
… that function isn’t being executed. To execute it, you must include
()
, like so:This is known as an immediately invoked function expression (IIFE).
The better solution though in this exact code sample is what you’ve already found… to unwrap that IIFE and just use the callback function. The IIFE is not needed here.
Also, be aware that web sockets support binary transfer. You do not need and should not stringify that data as JSON. The JSON version of that data is going to be huge… many times the size of the original data. It will also require significantly more CPU and memory to deal with, both client-side and server-side. You should write the ArrayBuffer to the socket instead.