Java音频循环3次

问题描述 投票:1回答:1

我需要在页面中重复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>
javascript loops audio
1个回答
0
投票

setTimeout的使用不需要包装在Promise中,您只需要进行设置即可触发下一个播放调用within 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();

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

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