Reputation: 15847
I have the below function that is part of a bigger function but I eliminated all of the parts that aren't part of the problem.
The function creates an audio tag and puts it in the body. I'm using this method instead of the audio API because I'm using createMediaElementSource
which requires the HTML element.
After the ended
event is finished and you click the replay
button, the play
function is called twice, despite only being triggered once.
I tried putting the code in a snippet, but I couldn't duplicate the problem so I had to put it in a fiddle instead. - https://jsfiddle.net/6n2f34eh/
On the full function, there is user interaction that activates the playing.
<button type="button" class="btn-replay">REPLAY</button>
var func = function() {
that = this;
that.sound;
this.init = function() {
document.querySelector(".btn-replay").addEventListener("click", that.play);
tag = document.createElement("audio");
tag.className = "player";
document.body.appendChild(tag);
that.sound = document.querySelector(".player");
that.sound.src = 'https://www2.cs.uic.edu/~i101/SoundFiles/CantinaBand3.wav';
that.sound.addEventListener("canplaythrough", this.play);
that.sound.addEventListener("ended", this.ended);
}
this.ended = function() {
console.log("ended")
}
this.play = function() {
console.log("play")
that.sound.play();
}
this.init();
}
test = new func();
Upvotes: 1
Views: 379
Reputation:
You've got two event listeners that result in the play function being called - "click" on the button and "canplaythrough" on the sound. Right after you click the button, the audio loads from the link so both events are fired.
Upvotes: 1