[英]Javascript stop and play different sounds
I'm building a simple web app in javascript with 3 buttons playing 3 different mp3 sounds. 我正在用javascript构建一个简单的网络应用程序,其中包含3个按钮,可播放3种不同的mp3声音。 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?
如果我按下按钮1,然后按下按钮2,我需要声音1停止并播放声音2。我该如何做?
my code: 我的代码:
Javascript: 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: 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 提前致谢
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=[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.