How to loop sound in JavaScript?

旧城冷巷雨未停 提交于 2019-12-30 18:55:49

问题


I tried below code to play a sound in JavaScript for certain times but with no success, the sound plays just once, what is the problem?

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

Function:

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

HTML code:

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

回答1:


If you want to play the sound infinitely use the attribute loop in the tag audio :

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

Edit

If you want to stop the loop after 3 times, add an event listener :

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);


来源:https://stackoverflow.com/questions/22492900/how-to-loop-sound-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!