【发布时间】:2012-10-18 01:57:24
【问题描述】:
我在 Chrome 中的游戏中使用网络音频 API。为了播放声音,我使用了网络音频 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,你能写一些代码示例吗?我对编码知之甚少。所以...
-
请注意,
createMediaElementSource目前仅在 Chrome 中完全有效。 AnalyzerNode 只会在 Chrome 上填充正确的数据,在 Safari 上,数据将始终为空(或者更确切地说,全为 0)。
标签: javascript html google-chrome audio html5-audio