javascript中的异步播放声音?

Sca*_*pat 4 javascript audio jquery 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
Run Code Online (Sandbox Code Playgroud)

Sound1 和 Sound2 持续不到 5 秒 演算持续 1 秒。

我怎样才能在 javascript 中做到这一点?

我必须在 HTML5 中使用 Workers 吗?

谢谢。

dor*_*ack 6

在 JS 中异步播放声音实际上非常简单。您只需要立即创建s 和它们,而不是ing 全局对象。下面是一个例子:new Audioplay()play()Audio

function playSoundAsync(url){
    new Audio(url).play();
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您的代码将如下所示(使用setIntervals 和setTimeouts 来同步声音):

function playSoundAsync(url){
    new Audio(url).play();
}
Run Code Online (Sandbox Code Playgroud)
// 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);
Run Code Online (Sandbox Code Playgroud)

此外,当您Play ${sound} individually快速单击按钮时,您可能会注意到这一点: ${sound} 的新播放开始,无需等待或中断当前的 ${sound} 播放!这允许您创建这样的声学混乱:

<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>
Run Code Online (Sandbox Code Playgroud)
var cacophony = setInterval(function(){new Audio('https://audio.code.org/win3.mp3').play();}, 25);
Run Code Online (Sandbox Code Playgroud)

  • 您需要处理承诺,除非您收到类似“Uncaught (in promise) DOMException”这样的错误 (2认同)

mab*_*rif 5

通过使用 JS Promise 和异步函数,您可以轻松地使音频播放异步(无需使用计时器)。

// makes playing audio return a promise
function playAudio(audio){
  return new Promise(res=>{
    audio.play()
    audio.onended = res
  })
}

// how to call
async function test(){
  const audio = new Audio('<url>')
  await playAudio(audio)
  // code that will run after audio finishes...
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案 (2认同)

WoI*_*IIe 0

也许您正在寻找window.setInterval()