为什么在提示后执行音频?

问题描述 投票:1回答:1
function myTimer() {
    randint= Math.floor(Math.random() * 10)+1;
    randstimuli=gorilla.stimuliURL(dict[randint]);
    var audio = new Audio(randstimuli);
    audio.play();
    var start=Date.now();
    var ans=prompt("was the last number the same as the one two steps ago");
    console.log(Date.now()-start);
}

我具有播放声音并通过提示符向用户提问的功能。当我运行该功能时,即使在代码中提示之前有音频,也会在回答提示后立即播放声音。由于Java脚本的单线程性质,由于音频长度的假设,我假设音频异步运行。

我的音频很短,只包含一个字。我希望它们在提示打开之前完成。

javascript asynchronous audio prompt single-threaded
1个回答
1
投票

您可以侦听onendedaudio事件并在回调中执行操作。

示例:


function myTimer() {
   randint = Math.floor(Math.random() * 10) + 1;
   randstimuli = gorilla.stimuliURL(dict[randint]);
   var audio = new Audio(randstimuli);
   audio.play();
   audio.onended = function () {
      var start = Date.now();
      var ans = prompt("was the last number the same as the one two steps ago");
      console.log(Date.now() - start);
   }

}
© www.soinside.com 2019 - 2024. All rights reserved.