我知道有关于这个的线程,但我想知道我在这个特定脚本中更改了什么以使音频在另一个脚本启动时暂停。非常感谢。
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();
}
}
您需要以某种方式记住上次播放的声音对象(保留对它的引用(并在播放下一个声音之前暂停它。我做了简单的片段,我使用了一些我在网上找到的声音:
var players = [{mp3: null}, {mp3: null}, {mp3: null}];
var currentAudio = null;
function playSound(el,soundfile) {
if(currentAudio){
currentAudio.pause();
}
if (el.mp3) {
if(el.mp3.paused){
currentAudio = el.mp3;
el.mp3.play();
} else {
el.mp3.pause();
}
} else {
el.mp3 = new Audio(soundfile);
currentAudio = el.mp3;
el.mp3.play();
}
}
document.getElementById('player1Button').addEventListener('click', function(){
playSound(players[0], 'http://www.sousound.com/music/healing/healing_01.mp3');
});
document.getElementById('player2Button').addEventListener('click', function(){
playSound(players[1], 'https://www.nasa.gov/mp3/590189main_ringtone_131_launchNats.mp3');
});
document.getElementById('player3Button').addEventListener('click', function(){
playSound(players[2], 'https://www.nasa.gov/mp3/581097main_STS-1_Dust-it-Off.mp3');
});
document.getElementById('stop').addEventListener('click', function(){
if(currentAudio){
currentAudio.pause();
}
});
<button id="player1Button">Play 1</button>
<button id="player2Button">Play 2</button>
<button id="player3Button">Play 3</button>
<button id="stop">Stop</button>
请注意,暂停时,如果从上次暂停的位置再次播放声音,声音将恢复,如果您希望它停止,因此请暂停并快退,以便从头开始再次播放,您需要在暂停后将 Audio 对象的currentTime
设置为 0:currentAudio.currentTime = 0;