Reputation: 134
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.)
Upvotes: 0
Views: 686
Reputation: 136708
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:
onaudioprocess
event. 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>
Upvotes: 2