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.
const audioCtx = new (window.AudioContext || window.webkitAudioContext)();
const button = document.querySelector("button");
const pre = document.querySelector("pre");
const myScript = document.querySelector("script");
pre.innerHTML = myScript.innerHTML;
const channels = 2;
const frameCount = audioCtx.sampleRate * 2.0;
const myArrayBuffer = audioCtx.createBuffer(
channels,
frameCount,
audioCtx.sampleRate,
);
button.onclick = () => {
for (let channel = 0; channel < channels; channel++) {
const nowBuffering = myArrayBuffer.getChannelData(channel);
for (let i = 0; i < frameCount; i++) {
nowBuffering[i] = Math.random() * 2 - 1;
}
}
const source = audioCtx.createBufferSource();
source.buffer = myArrayBuffer;
source.connect(audioCtx.destination);
source.start();
};