I don't know why, but I can't figure out why this does not work. I've been sitting for hours trying different methods, reading and watching videos on the subject, but I still can not figure it out.
Q: Why does a "new" audio file start playing, overlapping the previous one, every time I click the element? Should my if statement not take care of that?
document.getElementById("chatWrapper").addEventListener("click", playSound);
function playSound() {
//alert("Success!");
var sEE0 = new Audio('../sound/00-menu-music.mp3');
sEE0.volume = 0.2;
if (sEE0.duration > 0) {
return;
} else {
sEE0.play();
}
}
How do I solve this? Thanks in advance!
like @frontend_dev said, one of your problem is the variable scoping, other is you are checking using
sEE0.duration
, but that would give you the length of the audio file, which is bound to be bigger than0
, may be that's why it is not playing, what you are looking for iscurrentTime
, the if condition should beif (sEE0.duration > 0) {
,but I would prefer checking if the audio is playing or paused, rather than checking till what part the audio has played( unless the usecase requires that)
I would re-write the code as: