Play PCM as it is being generated

613 views Asked by At

I am generating some raw audio data in javascript and I need to play it as I am generating it. I searched for this here and the closest thing to what I am looking for is this. However, in the answer given there the array of data points is generated first and then the audio is played. I need to play it while generating it. Basically I am receiving some stream of some other data, processing it and generating the audio based on that. I need to play the audio corresponding to the data I am receiving as I am receiving it. (A simplified example is receiving the audio volume and frequency.)

1

There are 1 answers

1
Kaiido On

If I'm getting the request correctly, then all you need is a ScriptProcessorNode.
You will feed it with your PCM data in the following way:

  • wait for its onaudioprocess event.
  • get the outputBuffer from the event which is an AudioBuffer.
  • loop through each channels of the outputBuffer (will return an Float32Array).
  • loop through all the samples of the outputBuffer's channels data.
  • set your own data

function makeSomeNoise() {
  var ctx = new AudioContext();
  var processor = ctx.createScriptProcessor(4096, 1, 1);
  processor.onaudioprocess = function(evt) {
    var outputBuffer = evt.outputBuffer;
    // Loop through the output channels
    for (var channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
      var outputData = outputBuffer.getChannelData(channel);
      // Loop through the 4096 samples
      for (var sample = 0; sample < outputBuffer.length; sample++) {
        outputData[sample] = ((Math.random() * 2) - 1) * 0.5;
      }
    }
  };
  processor.connect(ctx.destination);
}

btn.onclick = function() {
  if (confirm("That won't be really nice"))
    makeSomeNoise();
}
<button id="btn">make some noise</button>