Jan de Vries Jan de Vries - 2 months ago 10
Javascript Question

html5 audio addeventhandler

I made a html5 audioplayer with a limited loop function, but I can't manage to keep this functionality when I want to replace the audioplayer with buttons and adding an eventhandler to them. In this example the checkbox had to be checked and the 2nd option of the selectmenu must be selected, before the repeatfunction works. Somehow the repeat-function stops working when I add:
"document.getElementById("Play").addEventListener("click", myFunction);". If I remove it, the code works, but only when I use the html audioplayer itself.
My code:

<!DOCTYPE html>
<html>
<body>

<span style="font-family:arial; font-size:16px;"><b>Pre:</b></span>
<input id="precount" type="checkbox"><br><br>
<span style="font-family:arial; font-size:16px;"><b>Repeat:</b></span>
<select>
<option id="ok1">1x</option>
<option id="ok2">2x</option>
<option id="ok3">3x</option>
</select><br><br>

<audio id="myAudio" controls>
<source src="http://u1259p183.web0080.zxcs.nl/jQuery.mmenu-master/demo/sortablemenumobile/range_items/audio_notes/10_a.mp3">
</audio>

<script>
function PlaySound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.play();
}
function PauseSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.pause();
}
</script>

<form>
<input type="button" value="PlaySound" id="Play">
<input type="button" value="PauseSound" id="Pause">
</form>


<script>

document.getElementById("Play").addEventListener("click", function);
var loopLimit = 2;
var loopCounter = 0;
var aud = document.getElementById("myAudio");
aud.onended = function() {
if ((loopCounter < loopLimit) && (document.getElementById("ok2").selected==true) &&(document.getElementById("precount").checked==true)){
this.currentTime = 0;
this.play();
loopCounter++;
}
};
</script>

</body>
</html>

Answer

Change line with event listener to:

document.getElementById("Play").addEventListener("click", function (){
    PlaySound("myAudio")
});