如何在 javascript 中异步加载声音?
我想同时循环播放多个声音和微积分。 这是时间线:
10 seconds 7 seconds 10 seconds
|--------------------|------------------|--------------------|--- etc
| Sound1 playing |Sound2 playing | Sound1 playing |--- etc
| Do a calculus |Do a calculus | Do a calculus |--- etc
Sound1 和 Sound2 持续不到 5 秒 计算持续 1 秒。
我如何在 javascript 中做到这一点?
我必须在 HTML5 中使用 Workers 吗?
谢谢。
最佳答案
用JS异步播放声音其实很简单。你只需要创建 new <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement" rel="noreferrer noopener nofollow">Audio</a>
s 和 play()
他们马上而不是play()
ing 全局Audio
对象。这是一个例子:
function playSoundAsync(url){
new Audio(url).play();
}
因此,在您的情况下,您的代码将如下所示(使用涉及 setInterval
和 setTimeout
的 hack 来同步声音):
// For simplicity I'll use MP3 files readily available on the Internet
var sound1url = 'https://audio.code.org/win3.mp3';
var sound2url = 'https://audio.code.org/failure3.mp3';
var calculusUrl = 'https://audio.code.org/failure1.mp3';
setInterval(function() {
new Audio(sound1url).play();
new Audio(calculusUrl).play();
}, 17000);
setTimeout(function() {
setInterval(function() {
new Audio(sound2url).play();
new Audio(calculusUrl).play();
}, 17000);
}, 10000);
<button onclick="new Audio(sound1url).play();">Play sound1 individually</button>
<button onclick="new Audio(sound2url).play();">Play sound2 individually</button>
<button onclick="new Audio(calculusUrl).play();">Play calculus individually</button>
此外,当您快速点击 Play ${sound} individually 按钮时,您可能会注意到这一点:新的 ${sound} 播放开始而不等待或中断当前的 ${sound}回放!这允许您创建一个像这样的声音困惑:
var cacophony = setInterval(function(){new Audio('https://audio.code.org/win3.mp3').play();}, 25);
<button onclick="clearInterval(cacophony);">Click here to stop this cacophony</button>
关于javascript - 在javascript中异步播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567426/