我正在用 javascript 构建一个简单的 Web 应用程序,其中有 3 个按钮播放 3 种不同的 mp3 声音。我有点被逻辑困住了。如果我先播放按钮 1,然后再播放按钮 2,我需要声音 1 来停止并播放声音 2。我该怎么做?
我的代码:
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>
提前致谢
最佳答案
将播放的音频存储在数组中:
var playing=[];
//when played
playing.push(el.mp3);
现在您可以使整个数组静音:
playing.forEach(el=>el.pause());
playing=[];
关于Javascript 停止并播放不同的声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41594935/