Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an AudioBuffer from a Blob?

I have an audio file/blob that has been created using the MediaRecorder api:

let recorder = new MediaRecorder(this.stream)
let data = [];
recorder.ondataavailable = event => data.push(event.data);

and then later when the recording is finished:

let superBlob = new Blob(data, { type: "video/webm" });

How can I use this blob to create an AudioBuffer? I need to either :

  • Transform the Blob object into an ArrayBuffer which I could use with AudioContext.decodeAudioData (returns an AudioBuffer) or
  • Transform the Blob object into an Float32Array, where I could copy it into the AudioBuffer with AudioBuffer.copyToChannel()

Any tips on how to achieve that are appreciated. Cheers!

like image 526
Maxime Dupré Avatar asked Nov 01 '16 15:11

Maxime Dupré


2 Answers

To convert a Blob object to an ArrayBuffer, use FileReader.readAsArrayBuffer.

let fileReader = new FileReader();
let arrayBuffer;

fileReader.onloadend = () => {
    arrayBuffer = fileReader.result;
}

fileReader.readAsArrayBuffer(superBlob);
like image 111
Maxime Dupré Avatar answered Oct 11 '22 20:10

Maxime Dupré


The accepted answer is great but only gives an array buffer which is not an audio buffer. You need to use the audio context to convert the array buffer into an audio buffer.

const audioContext = AudioContext()
const fileReader = new FileReader()

// Set up file reader on loaded end event
fileReader.onloadend = () => {

    const arrayBuffer = fileReader.result as ArrayBuffer

    // Convert array buffer into audio buffer
    audioContext.decodeAudioData(arrayBuffer, (audioBuffer) => {

      // Do something with audioBuffer
      console.log(audioBuffer)

    })

}

//Load blob
fileReader.readAsArrayBuffer(blob)

I wish the answer had included an example using decodeAudioData. I had to find it somewhere else and I thought since this is the top search for "Blob to Audio Buffer" I would add some helpful information for the next person that comes down this rabbit hole.

like image 21
PAT-O-MATION Avatar answered Oct 11 '22 20:10

PAT-O-MATION