AudioContext.createBufferSource()
åºçº¿
广æ³å¯ç¨
èª 2021å¹´4æ èµ·ï¼æ¤ç¹æ§å·²å¨ä¸»æµæµè§å¨ä¸å¾å°æ¯æï¼å¯å¨å¤§å¤æ°è®¾å¤åæµè§å¨çæ¬ä¸æ£å¸¸ä½¿ç¨ã
createBufferSource() æ¹æ³ç¨äºå建ä¸ä¸ªæ°çAudioBufferSourceNodeæ¥å£ï¼è¯¥æ¥å£å¯ä»¥éè¿AudioBuffer å¯¹è±¡æ¥ææ¾é³é¢æ°æ®ãAudioBuffer对象å¯ä»¥éè¿AudioContext.createBuffer æ¥å建æè
éè¿ AudioContext.decodeAudioDataæåè§£ç é³è½¨åè·åã
è¯æ³
js
var audioCtx = new AudioContext();
var source = audioCtx.createBufferSource();
è¿å
ä¸ä¸ªAudioBufferSourceNode对象ã
ä¾å
å¨è¿ä¸ªä¾åä¸ï¼æä»¬å°ä¼å建ä¸ä¸ª 2 ç§çç¼å²å¨ï¼å¹¶ç¨ç½åªé³å¡«å
å®ï¼ç¶åéè¿AudioBufferSourceNodeæ¥ææ¾å®ã
夿³¨ï¼You can also run the code live, or view the source.
js
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;
// Stereo
var channels = 2;
// Create an empty two second stereo buffer at the
// sample rate of the AudioContext
var frameCount = audioCtx.sampleRate * 2.0;
var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
button.onclick = function () {
// Fill the buffer with white noise;
//just random values between -1.0 and 1.0
for (var channel = 0; channel < channels; channel++) {
// This gives us the actual ArrayBuffer that contains the data
var nowBuffering = myArrayBuffer.getChannelData(channel);
for (var i = 0; i < frameCount; i++) {
// Math.random() is in [0; 1.0]
// audio needs to be in [-1.0; 1.0]
nowBuffering[i] = Math.random() * 2 - 1;
}
}
// Get an AudioBufferSourceNode.
// This is the AudioNode to use when we want to play an AudioBuffer
var source = audioCtx.createBufferSource();
// set the buffer in the AudioBufferSourceNode
source.buffer = myArrayBuffer;
// connect the AudioBufferSourceNode to the
// destination so we can hear the sound
source.connect(audioCtx.destination);
// start the source playing
source.start();
};
è§è
| è§è |
|---|
| Web Audio API > # dom-baseaudiocontext-createbuffersource > |