7

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>
Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
user3427977
  • 115
  • 1
  • 1
  • 8
  • I think essentially you aren't waiting for the sound to finish. The for loop runs very quickly, and you only hear the last one. Try waiting a little after "PlaySound" or using an event to detect when it's finished playing. – Matthew Wilcoxson Mar 18 '14 at 23:07
  • what's your suggestion? how to make a delay between sounds? – user3427977 Mar 18 '14 at 23:08

1 Answers1

6

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);
R3tep
  • 12,512
  • 10
  • 48
  • 75