如何用JavaScript控制多个音频播放器?

时间:2015-08-27 17:25:36

标签: javascript jquery audio

我在同一个网页上创建了两个音频播放器。

<audio id="player0">
<button id="play0" /><button id="forward0" />
<button id="backward0" /></audio> <audio id="player1">
<button id="play1" />
<button id="forward1" /><button id="backward1" />
</audio>

但是当我点击“play0”时,他们都会玩。我认为问题是我将eventListener绑定到一个playbtn。有人可以告诉我如何取消绑定eventListener,这样我一次只能玩一个吗?

var index = 0; 
var playbtn = document.getElementById("play-images-"+index);
var playbtn.addEventListener("click", playPause, false);
index++;

function playPause(){
    playbtn = document.getElementById("play"+index);
    if(!audio.paused && !audio.ended){
                audio.pause();
    }else{
                audio.play();
    }
}

1 个答案:

答案 0 :(得分:1)

这应该接近你所需要的......

HTML

<audio id="player0">
<button id="play0" />
<button id="forward0" />
<button id="backward0" />
</audio>
<audio id="player1">
<button id="play1" />
<button id="forward1" /><button id="backward1" />
</audio>

的JavaScript

// init page when window loads
window.addEventListener('load', initPage, false);

function initPage() {
  // add click event to play buttons
  var btnColl = document.getElementsByTagName('button');
  for (var i = 0; i < btnColl.length; i++) {
    if (btnColl[i].id.indexOf('play')> -1) {
      btnColl[i].addEventListener('click', playPause, false);
    }
  }
}

function playPause(sender) {
  // get audio player based on button id
  var audioPlayer = document.getElementById(sender.srcElement.id.replace('play', 'player'));
  if(!audioPlayer.paused && !audioPlayer.ended){
    audioPlayer.pause();
  }else{
    audioPlayer.play();
  }
}