Mauro74
Mauro74

Reputation: 4826

Javascript stop and play different sounds

I'm building a simple web app in javascript with 3 buttons playing 3 different mp3 sounds. I'm bit stuck with the logic. If I play button 1 then button 2 I need the sound 1 to stop and play sound 2. How do I do that?

my code:

Javascript:

function playSound(el, soundfile) {
    if (el.mp3) {
        if(el.mp3.paused) el.mp3.play();
        else el.mp3.pause();
    } else {
        el.mp3 = new Audio(soundfile);
        el.mp3.play();
    }
}

HTML:

<a class="btn" onclick="playSound(this, 'sounds/sound-1.mp3');">sound 1</a>
<a class="btn" onclick="playSound(this, 'sounds/sound-2.mp3');">sound 2</a>
<a class="btn" onclick="playSound(this, 'sounds/sound-3.mp3');">sound 3</a>

Thanks in advance

Upvotes: 0

Views: 106

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138267

Store the played audios in an array:

var playing=[];

//when played
playing.push(el.mp3);

Now you can silence the whole array:

playing.forEach(el=>el.pause());
playing=[];

Upvotes: 1

Related Questions