The createBufferSource()
method of the BaseAudioContext
Interface is used to create a new AudioBufferSourceNode
, which can be used to play audio data contained within an AudioBuffer
object. AudioBuffer
s are created using BaseAudioContext.createBuffer
or returned by BaseAudioContext.decodeAudioData
when it successfully decodes an audio track.
In this example, we create a two second buffer, fill it with white noise, and then play it via an AudioBufferSourceNode
. The comments should clearly explain what is going on.
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var button = document.querySelector('button');
var pre = document.querySelector('pre');
var myScript = document.querySelector('script');
pre.innerHTML = myScript.innerHTML;
var channels = 2;
var frameCount = audioCtx.sampleRate * 2.0;
var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
button.onclick = function() {
for (var channel = 0; channel < channels; channel++) {
var nowBuffering = myArrayBuffer.getChannelData(channel);
for (var i = 0; i < frameCount; i++) {
nowBuffering[i] = Math.random() * 2 - 1;
}
}
var source = audioCtx.createBufferSource();
source.buffer = myArrayBuffer;
source.connect(audioCtx.destination);
source.start();
}