如何在JavaScript中循环声音

How to loop sound in JavaScript?

本文关键字:循环 声音 JavaScript      更新时间:2023-09-26

我尝试下面的代码在JavaScript中播放声音,但没有成功,声音只播放一次,问题是什么?

for(var i = 0; i < errors; i++){
    PlaySound3();
}

功能:

function PlaySound3() {
    var audioElement = document.getElementById('beep');
    audioElement.setAttribute("preload", "auto");
    audioElement.autobuffer = true;    
    audioElement.load();
    audioElement.play();
};
HTML代码:

<audio id="beep">
    <source src="assets/sound/beep.wav" type="audio/wav" />
</audio>

如果您想无限播放声音,请在标签audio:

中使用属性loop
<audio id="beep" loop>
   <source src="assets/sound/beep.wav" type="audio/wav" />
</audio>

编辑

如果你想在3次之后停止循环,添加一个事件监听器:

HTML:

<audio id="beep">
   <source src="assets/sound/beep.wav" type="audio/wav" />
</audio>

JS:

var count = 1
document.getElementById('beep').addEventListener('ended', function(){
   this.currentTime = 0;
   if(count <= 3){
      this.play();
   }
   count++;
}, false);