播放新声音时暂停当前声音css,html5 - audio,onclick

时间:2017-03-22 19:53:07

标签: html5 audio onclick

我知道有关于此的线索,但我想知道我在这个特定的脚本中改变了什么,以便在另一个启动时让音频暂停。非常感谢。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

你需要以某种方式记住上次播放的声音对象(保持对它的引用)并在你播放下一个声音之前暂停它。我制作了简单的片段,我使用了一些我在网上找到的声音:



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>
&#13;
&#13;
&#13;

请注意,暂停时,如果要从暂停的最后一个位置再次播放声音,将恢复声音,如果您希望它停止,那么暂停和倒回以便从头开始再次播放,您需要设置{暂停后,Audio对象的{1}}为0:currentTime