8

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>
2
  • 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. Commented Mar 18, 2014 at 23:07
  • what's your suggestion? how to make a delay between sounds? Commented Mar 18, 2014 at 23:08

1 Answer 1

7

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I want to loop the sound just for certain times not forever
When you want to stop the loop, change the attribute 'loop' to false with javascriptp.
I want to stop looping for example after sound plays for 3 times, how can I know that sound play for 3 so I set track.loop = false ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.