Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++){
    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>
like image 397
user3427977 Avatar asked Mar 18 '14 23:03

user3427977


People also ask

How do I add JavaScript to a sound file?

Code snippet 4: Add <script> tags to the basic sound.html document to allow inserting JavaScript In addition to adding the <script> tags, we’ve added an id attribute to the <audio> element. This will allow us to pull the element into our JavaScript code.

How to play the beep sound infinitely in HTML?

5 If you want to play the sound infinitely use the attribute loopin the tag audio : <audio id="beep" loop> <source src="assets/sound/beep.wav" type="audio/wav" /> </audio>

What does the loop property do in JavaScript?

The loop property sets or returns whether an audio should start playing over again when it is finished. This property reflects the <audio> loop attribute. When present, it specifies that the audio should start playing over again when it is finished. false - Default. Indicates that the audio should NOT start playing again when it is finished

What is JavaScript audio and why is it important?

JavaScript Audio, when used correctly, can be an important component in digital learning content. Sound can be used to give feedback, add drama, and even make learning content more accessible. Every contemporary authoring environment integrates sound.


1 Answers

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);
like image 65
R3tep Avatar answered Sep 29 '22 00:09

R3tep