Reputation: 4826
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
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