BaseAudioContext: createBufferSource() method
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.
Syntax
Parameters
Return value
Examples
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();
};
Specifications
Browser compatibility
|
Desktop |
Mobile |
|
Chrome |
Edge |
Firefox |
Internet Explorer |
Opera |
Safari |
WebView Android |
Chrome Android |
Firefox for Android |
Opera Android |
Safari on IOS |
Samsung Internet |
createBufferSource |
14 |
12 |
25 |
No |
15 |
6 |
4.4.3 |
18 |
25 |
14 |
6 |
1.0 |
See also