javascript Web 音频 API:如何播放和停止音频?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13110007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Web audio API: how to play and stop audio?
提问by kikkpunk
i use web audio API in my game in Chrome. To play the sound, I use web audio API.
我在 Chrome 的游戏中使用网络音频 API。为了播放声音,我使用了网络音频 API。
I learn it from the article: http://www.html5rocks.com/en/tutorials/webaudio/intro/
我从文章中了解到: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);
}
However, the sounds weren't played. Let alone i want to use noteOff(0)to stop them later.
但是,没有播放声音。更不用说我想稍后使用noteOff(0)来阻止它们。
Then i found this article http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs
然后我发现这篇文章http://updates.html5rocks.com/2012/02/HTML5-audio-and-the-Web-Audio-API-are-BFFs
And i change my code to:
我将代码更改为:
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);
This time it is played!
这次玩了!
And here comes my problem: I want to stop the sound with a button.
我的问题来了:我想用按钮停止声音。
I tried to change the audio0.autoplay =false;
我试图改变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;}
});
In stead of getting stop, it is played again every time i click the button.
每次我单击按钮时,它都会再次播放,而不是停止播放。
Two questions:
两个问题:
what's the difference between those two playing audio methods?
How can i stop the sound manually?
这两种播放音频的方法有什么区别?
如何手动停止声音?
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by pimvdb
You can pause the audio element and set its time to 0
, so that you effectively have "stop" functionality: http://jsfiddle.net/Z5ZuJ/.
您可以暂停音频元素并将其时间设置为0
,以便您有效地拥有“停止”功能:http: //jsfiddle.net/Z5ZuJ/。
audio0.pause();
audio0.currentTime = 0;