我在Chrome浏览器中使用Web Audio API来制作我的游戏。为了播放声音,我使用了Web Audio API。
我从这篇文章中学习了如何使用:http://www.html5rocks.com/en/tutorials/webaudio/intro/
window.onload = init;
var context;
var bufferLoader;
function init() {
context = new webkitAudioContext();
bufferLoader = new BufferLoader(
context,
[
'0.mp3',
'2.mp3',
],
finishedLoading
);
bufferLoader.load();
}
function finishedLoading(bufferList) {
var source1 = context.createBufferSource();
var source2 = context.createBufferSource();
source1.buffer = bufferList[0];
source2.buffer = bufferList[1];
source1.connect(context.destination);
source2.connect(context.destination);
source1.noteOn(0);
source2.noteOn(0);
}
然而,声音并没有播放。更不用说我想稍后使用 noteOff(0) 来停止它们了。
然后我发现了这篇文章:http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs 于是我改变了我的代码为:
var context = new webkitAudioContext();
var analyser = context.createAnalyser();
var source;
var audio0 = new Audio();
audio0.src = '0.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
这次播放了!
现在我遇到了问题:我想用一个按钮停止声音。
我尝试更改 audio0.autoplay = false;
var play0 = false;
$("#0").click(function(){
if(play0===false){
audio0.src = '0.mp3';
audio0.controls = true;
audio0.autoplay = true;
audio0.loop = true;
source = context.createMediaElementSource(audio0);
source.connect(analyser);
analyser.connect(context.destination);
play0=true;}
if(paly0){
audio0.autoplay=false;}
});
每次我点击按钮,音频都会重新播放而非停止。
两个问题:
这两种播放音频的方式有什么区别?
如何手动停止声音?
非常感谢您的帮助。
audio0.pause()
吗? - pimvdb.pause()
和.currentTime = 0
组合使用。 - pimvdb