Web Audio API - How do I save the audio buffer to a file including all changes?

Viewed 768

I made changes to an audio buffer like gain and panning, connected them to an audio context. Now I want to save to a file with all the implemented changes. Saving the buffer as is would give me the original audio without the changes.

Any idea of a method or a procedure existed to do that?

2 Answers

On way is to use a MediaRecorder to save the modified audio.

So, in addition to connecting to the destination, connect to a MediaStreamDestinationNode. This node has a stream object that you can use to initialize a MediaRecorder. Set up the recorder to save the data when data is available. When you're down recording, you have a blob that you can then download.

Many details are missing here, but you can find out how to use a MediaRecorder using the MDN example.

I found a solution, with OfflineAudioContext. Here is an example with adding a gain change to my audio and saving it. On the last line of the code I get the array buffer with the changes I made. From there, I can go on saving the file.

let offlineCtx = new OfflineAudioContext(this.bufferNode.buffer.numberOfChannels, this.bufferNode.buffer.length, this.bufferNode.buffer.sampleRate);
let obs = offlineCtx.createBufferSource();
obs.buffer = this.buffer;
let gain = offlineCtx.createGain();
gain.gain.value = this.gain.gain.value;
obs.connect(gain).connect(offlineCtx.destination);
obs.start();
let obsRES = this.ctx.createBufferSource();
await offlineCtx.startRendering().then(r => {
  obsRES.buffer = r;
});
Related