Skip to content Skip to sidebar Skip to footer

How To Loop Sound In Javascript?

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++){ Play

Solution 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 = 1document.getElementById('beep').addEventListener('ended', function(){
   this.currentTime = 0;
   if(count <= 3){
      this.play();
   }
   count++;
}, false);

Post a Comment for "How To Loop Sound In Javascript?"