Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render the audio from a synth to a buffer (array of PCM values) with the Web Audio API

I have a simple synth that plays a note for some length of time:

// Creating audio graph
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var oscillator = audioCtx.createOscillator();
var gainNode = audioCtx.createGain();
oscillator.connect(gainNode);
gainNode.connect(audioCtx.destination);

// Setting parameters
oscillator.type = "sine";
oscillator.frequency.value = 2500;

// Run audio graph
var currentTime = offlineCtx.currentTime;
oscillator.start(currentTime);
oscillator.stop(currentTime + 1);

How can I get the PCM data of the sound the synthesiser makes? I've managed to do this with audio samples by using decodeAudioData, but I can't find an equivalent for an audio graph that isn't based on loading a sample.

I specifically want to render the audio graph with the OfflineAudioContext since I only care about retrieving the PCM data as fast as possible.

Thanks!

like image 978
Navid Hallajian Avatar asked Sep 11 '25 16:09

Navid Hallajian


1 Answers

You say you want to use an offline context and then you don't actually use an offline context. So you should do

var offlineCtx = new OfflineAudioContext(nc, length, rate)

where nc = number of channels, length is the number of samples, and rate is the sample rate you want to use.

Create your graph, start everything and then do

offlineCtx.startRendering().then(function (buffer) {
  // buffer has the PCM data you want. Save it somewhere, 
  // or whatever
})

(I'm not sure all browsers support promises from an offline context. If not, use offlineCtx.oncomplete to get the data. See the spec.)

like image 115
Raymond Toy Avatar answered Sep 13 '25 07:09

Raymond Toy