addEventListener与媒体冲突

时间:2018-12-17 21:02:54

标签: javascript audio

我正在尝试为此找到解决方案: 我在页面上有很多元素,并且正在实现下面的代码,这些代码可以满足我的需求。

document.addEventListener(
  'play',
  function (evt) {
    if (document.$_currentlyPlaying) {
      document.$_currentlyPlaying.pause()
      document.$_currentlyPlaying.load()
    }
    document.$_currentlyPlaying = evt.target
  },
  true
)

与此有关的问题是,页面中也有一个循环视频文件,该文件也受此解决方案影响。因此,我只需要定位音频元素(或其他指定的元素)。我已经尝试过在课堂上使用它,但是它似乎不起作用:

var x = document.getElementsByClassName('class')
for (var i = 0; i < x.length; i++) {
  x[i].addEventListener(
    'play',
    function (evt) {
      if (x.$_currentlyPlaying) {
        x.$_currentlyPlaying.pause()
        x.$_currentlyPlaying.load()
      }
      x.$_currentlyPlaying = evt.target
    },
    true
  )
}

由于我对JS不太熟悉,并且正在尝试合并从搜索解决方案中找到的代码,因此我不确定自己在做什么错或怎么做我想做的事情。

1 个答案:

答案 0 :(得分:1)

互斥播放

  

“ ...在页面上有很多元素,并且正在实现下面的代码来满足我的需要。”

假定需要互斥播放(现在称为MEP)。 MEP是一组媒体播放器的共同行为,其中一个播放器开始播放其媒体时,其他播放器将暂停或停止播放。


LBYL

演示

详细信息在演示中进行了评论。

注意:音频可能听不到,但是您会注意到只有一个<audio>标签会播放,而另外两个会暂停并加载。转到此Plunker可获得完整功能的演示。

// Collect all <audio> tags into a NodeList
var clips = document.querySelectorAll('audio');

/* 
Loop through the NodeList and register each <audio>
to the playing event.
When triggered, callback function mep() is called.
*/
for (let i = 0; i < clips.length; i++) {
  clips[i].addEventListener('playing', mep);
}

function mep(e) {
  /* 
  e.target is the <audio> that started playing
  On each loop check if <audio> is NOT e.target
  and then pause and load it.
  */
  for (let i = 0; i < clips.length; i++) {
    if (clips[i] !== e.target) {
      clips[i].pause();
      clips[i].load();
    }
  }
}
video, section {
  float: left;
  width: 49%;
}
<video src='https://storage04.dropshots.com/photos6000/photos/1381926/20170326/005609.mp4' loop controls autoplay width='49%'></video>
<section>
  <audio src='https://od.lk/s/NzlfOTEyMzgyNF8/jerky.mp3' controls></audio>
  <audio src='https://od.lk/s/NzlfOTEwMzM5OV8/righteous.mp3' controls></audio>
  <audio src='https://od.lk/s/NzlfOTEyMzg0OV8/misty_forest.mp3' controls></audio>
</section>