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>
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.
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>
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
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With