Javascript音频循环3次
我需要在我的页面上重复一个声音3次。我通过下面的代码尝试了同样的方法。但是audio.play()似乎并不等待剪辑完成。请帮我做同样的事情Javascript音频循环3次,javascript,loops,audio,Javascript,Loops,Audio,我需要在我的页面上重复一个声音3次。我通过下面的代码尝试了同样的方法。但是audio.play()似乎并不等待剪辑完成。请帮我做同样的事情 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <
<!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>
文件
功能睡眠(ms){
返回新承诺(resolve=>setTimeout(resolve,ms));
}
异步函数播放(){
var audio=新音频文件('https://interactive-examples.mdn.mozilla.net/media/examples/t-rex-roar.mp3');
对于(让index=0;index来说,setTimeout
的使用不需要包装在承诺中,您只需要这样做,以便在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();
(编辑:添加了检查剪辑是否是第一次播放的功能,以便它可以立即播放,而不是等待延迟)使用setTimeout
不需要包含在承诺中,您只需要这样做,以便在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();
(编辑:添加了检查剪辑是否是第一次播放的功能,以便它可以立即播放,而不是等待延迟)嗨,我也尝试了同样的功能,但仍然是audio.play();
没有等待音频剪辑完成。我尝试使用更长的音频剪辑,但在音频播放之间调用了递归函数。添加了consol.log以了解它。这是等待指定的延迟,直到剪辑完成。这是您的初始代码试图对sleep()执行的操作的工作版本您好,我也试过同样的方法,但仍然是audio.play();
没有等待音频剪辑完成。我尝试使用更长的音频剪辑,但在音频播放之间调用了递归函数。添加了consol.log以了解它。这是等待指定的延迟,直到剪辑完成。这是您的初始代码试图对sleep()执行的操作的工作版本你写的方法。