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

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);
});
The problem is that the chunks emitted by the
MediaRecorderdon'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
AudioWorkletor with a library likeextendable-media-recorderwhich supports recording wav files.