我想写一个HTML5网络音频应用编程接口的基本脚本,可以播放一些音频文件。但我不知道如何卸载一个播放的音频并加载另一个。在我的脚本中,两个音频文件同时播放,但不是我想要的。
下面是我的代码:
var context,
soundSource,
soundBuffer;
// Step 1 - Initialise the Audio Context
context = new webkitAudioContext();
// Step 2: Load our Sound using XHR
function playSound(url) {
// Note: this loads asynchronously
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.responseType = "arraybuffer";
// Our asynchronous callback
request.onload = function() {
var audioData = request.response;
audioGraph(audioData);
};
request.send();
}
// This is the code we are interested in
function audioGraph(audioData) {
// create a sound source
soundSource = context.createBufferSource();
// The Audio Context handles creating source buffers from raw binary
soundBuffer = context.createBuffer(audioData, true/* make mono */);
// Add the buffered data to our object
soundSource.buffer = soundBuffer;
// Plug the cable from one thing to the other
soundSource.connect(context.destination);
// Finally
soundSource.noteOn(context.currentTime);
}
// Stop all of sounds
function stopSounds(){
// How can do this?
}
// Events for audio buttons
document.querySelector('.pre').addEventListener('click',
function () {
stopSounds();
playSound('http://thelab.thingsinjars.com/web-audio-tutorial/hello.mp3');
}
);
document.querySelector('.next').addEventListener('click',
function() {
stopSounds();
playSound('http://thelab.thingsinjars.com/web-audio-tutorial/nokia.mp3');
}
);发布于 2012-07-10 23:38:59
你应该预先加载声音到缓冲区一次,在启动时,并简单地重置AudioBufferSourceNode,每当你想要播放它。
要按顺序播放多个声音,您需要基于缓冲区各自的长度,使用noteOn(time)逐个安排它们。
要停止声音,请使用noteOff。
听起来你遗漏了一些基本的网络音频概念。此HTML5Rocks tutorial和FAQ中的示例详细描述了这一点(以及更多内容)。
https://stackoverflow.com/questions/11415555
复制相似问题