[英]Web audio API: how to play and stop audio?
i use web audio API in my game in Chrome. 我在Chrome游戏中使用网络音频API。 To play the sound, I use web audio 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. 任何帮助是极大的赞赏。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.