Convert ArrayBuffer to AudioBuffer

72 Views Asked by At

I'm want to record audio from browser using MediaRecorder convert the same into AudioBuffer to send it to server. It returns the first chunk as AudioBuffer but for subsequent chunks it is throwing the following error:

Uncaught (in promise) DOMException: Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data enter image description here

Code

let recorder = null;

const record = (stream) => {
    recorder = new MediaRecorder(stream, {
        mimeType: "audio/webm;codecs=opus"
    });
    recorder.start(500); // Starting the record
    recorder.ondataavailable = (e) => {
        var reader = new FileReader()
        reader.onloadend = () => {
            var audioContext = new AudioContext();
            var myArrayBuffer = reader.result;
            audioContext.decodeAudioData(myArrayBuffer, (audioBuffer) => {
                console.log(audioBuffer);
                // Uncaught (in promise) DOMException: Failed to execute 'decodeAudioData' on 'BaseAudioContext': Unable to decode audio data
            });
        };
        reader.readAsArrayBuffer(e.data);
    }
}

navigator.getUserMedia({
    audio: {
        channelCount: 1,
        sampleRate: 16000,
    }
}, record, (e) => {
    console.log(e);
});
1

There are 1 best solutions below

0
chrisguttandin On

The problem is that the chunks emitted by the MediaRecorder don't need to be valid files on their own. Only all chunks combined need to form a valid file.

On the other hand decodeAudioData() only works with full files.

The fact that it works with the first chunk is probably because it looks like a full file to the decoder.

But it looks like you want to send PCM data to the server anyway. In that case you can record PCM data directly using an AudioWorklet or with a library like extendable-media-recorder which supports recording wav files.