我有多个音频文件,使用以下 JavaScript 代码单击时会播放:
函数 playSound(el,声音文件) {
if (el.mp3) {
if(el.mp3.paused) el.mp3.play();
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
问题是,当单击两个时,两个音频文件将同时播放。我需要在单击第二个音频文件时停止播放第一个音频文件。
我需要在这段代码中添加什么。
最佳答案
我还没有使用过 HTML5 的声音 API,所以这只是为了表达我的观点。
所以,就像我在评论中所说的那样,您可以将所有元素添加到全局数组中并像这样暂停它们。
var audio = [];
function playSound(el,soundfile) {
// Pause all
if (el.mp3) {
if(el.mp3.paused) {
// Pause all sounds
pauseAllSounds();
el.mp3.play();
// Add the sound to the audio array
audio.push(el);
// You should probably clean up the audio array too,
// so no two identical audio files exists in the array,
// but that's up to you! :)
}
else el.mp3.pause();
} else {
el.mp3 = new Audio(soundfile);
el.mp3.play();
}
}
function pauseAllSounds(){
audio.forEach(function(el){
if(!el.mp3.paused) el.mp3.pause();
});
}
关于javascript - HTML 页面上有多个音频文件,一次只需要播放一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45088534/