javascript - 在javascript中异步播放声音?

标签 javascript jquery audio asynchronous

如何在 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();
}

因此,在您的情况下,您的代码将如下所示(使用涉及 setIntervalsetTimeout 的 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/

相关文章:

android - 更新搜索栏时选框无法工作

java - 如何查找SDCard上的所有音频文件(eclipse,android)

php - 在特定点将 PHP 变量传递给 Javascript

javascript - jQuery 幻灯片需要时间加载

vb.net - VB.NET:无法从资源加载音频

php - 使用 JavaScript 提交表单的问题

javascript - 第一次点击时提交按钮不起作用

javascript - 如何将图像从服务器加载到phonegap中的img文件夹中

javascript - 使用 Chrome 开发者选项卡进行实时 html 和 javascript 测试

javascript - 如何将图像附加到div,并在1秒内淡出图像?