【问题标题】:Javascript, play sounds within a loopJavascript,循环播放声音
【发布时间】:2021-05-31 06:16:32
【问题描述】:

我需要按顺序播放一系列声音。使用我当前的代码,声音几乎是一次播放而不是按顺序播放。我尝试了各种 setTimeout()、setInterval() 组合,但由于声音的长度不同,我无法完成这项工作。有没有办法可以设置一个条件标志来确保声音不重叠? sleep() 函数是唯一的答案吗?

function playAll()
{

for (i = 0; i < 10; i++) {
playSound(sound[i]);

// if sound is finished, continue loop
// need some type of flag?


}

}

【问题讨论】:

    标签: javascript loops audio sleep


    【解决方案1】:

    当元素停止播放时,HTMLAudioElements 会触发 ended 事件。如果你承诺 playSound 以便在元素上触发下一个 stop 事件时返回 Promise,你可以在循环内调用 await

    const playSound = soundElement => {
        soundElement.play();
        return new Promise((resolve) => {
            soundElement.addEventListener('ended', resolve)
        })
    }
    function playAll() {
        for (let i = 0; i < 10; i++) { // don't forget to declare the variable with `let`
            await playSound(sound[i]);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2022-12-31
      相关资源
      最近更新 更多