Web音频API:如何播放和停止音频?

5

我在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;}

    });

每次我点击按钮,音频都会重新播放而非停止。

两个问题:

  1. 这两种播放音频的方式有什么区别?

  2. 如何手动停止声音?

非常感谢您的帮助。


你想要 audio0.pause() 吗? - pimvdb
没有停止,所以按照pimvdb建议的暂停它。 - Ian Devlin
1
你可以将.pause().currentTime = 0组合使用。 - pimvdb
最终有什么区别呢? - 3pic
请查看库 https://github.com/vjai/musquito,它可以帮助更轻松地使用HTML5音频或Web音频播放声音。 - VJAI
显示剩余4条评论
1个回答

7
您可以暂停音频元素并将其时间设置为0,从而实现“停止”功能:http://jsfiddle.net/Z5ZuJ/
audio0.pause();
audio0.currentTime = 0;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接