我需要在页面上重复3次声音。我尝试通过下面的代码相同。但是audio.play()似乎没有等待剪辑完成。请帮忙。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script>
        function sleep(ms) {
            return new Promise(resolve => setTimeout(resolve, ms));
        }
        async function play() {

            var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
            for (let index = 0; index <3; index++) {

                await sleep(1000);
                await console.log(index)
                await audio.play();

            }

        }
    </script>
</head>
<body>

  <button type='button' onclick="play()">Play</button>


</body>
</html>

最佳答案

无需将setTimeout的使用包装在Promise中,您只需要进行设置即可,以便在setTimeout回调中触发下一个播放调用。我建议使用递归函数:

function playSound(audio, numberOfTimes = 1, delay = 3000, firstTime = true ){
    if(firstTime){
       audio.play();
    }
    setTimeout( () => {
       if(!firstTime){
           audio.play();
       }
       numberOfTimes--;
       if(numberOfTimes > 0){
         playSound(audio,numberOfTimes,delay, false);
       }
    }, delay)
  }

  function playTRexRoar() {
        var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
        playSound(audio,3,3000);
    }

  playTRexRoar();

(编辑:添加了检查是否是第一次播放剪辑,以便可以立即播放而不是等待延迟)

关于javascript - Javascript音频循环3次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60340744/

10-08 21:15