Why does a new audio file start playing if one is already playing? (JS)

128 views Asked by At

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!

2

There are 2 answers

0
mido On

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 than 0, may be that's why it is not playing, what you are looking for is currentTime, the if condition should be if (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:

document.getElementById("chatWrapper").addEventListener("click", playSound);
var sEE0 = new Audio('../sound/00-menu-music.mp3');
sEE0.volume = 0.2;
function playSound() {
    //alert("Success!");
    if (sEE0.paused) {
        sEE0.play();
    }
}
4
frontend_dev On

You seem to be creating a new audio element each time you click.

Try to initialize it only once: (attn, quick'n'dirty!)

document.getElementById("chatWrapper").addEventListener("click", playSound);
var sEE0 = new Audio('../sound/00-menu-music.mp3');
function playSound() {
    //alert("Success!");
    sEE0.volume = 0.2;
    if (sEE0.duration > 0) {
        return;
    } else {
        sEE0.play();
    }
}