我需要在页面中重复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中,您只需要进行设置即可触发下一个播放调用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();
((编辑:添加了检查是否是第一次播放剪辑,以便可以立即播放而不是等待延迟)