JS - 防止多个音频文件同时播放

JS - preventing several audio files from playing at the same time

我编写了一个遍历数组的函数,创建了一个 querySelector、一个 audio 元素,以及 addsEventListener 以在单击按钮时播放音频元素。

我的问题是我不知道如何一次只播放一首曲目。理想的行为是当用户点击一个按钮时,所有其他曲目停止或暂停。

我尝试按照我在 SO 中找到的类似解决方案中的建议使用 for 循环,但它没有用。我想我没有将它添加到应该控制流量的位置。

非常感谢任何帮助,谢谢。

const tracks = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
// 

const newAudioTracks = () => {
  tracks.forEach(function(track) {
    const button = document.querySelector(`#track-${track}`);
    const musicTrack = new Audio(`/music/track${track}.mp3`);
    musicTrack.id = track;
    button.addEventListener('click', (event) => {
      event.preventDefault();
      musicTrack.paused ? musicTrack.play() : musicTrack.pause();
    })
  })
}

newAudioTracks();

问题是您的事件只会针对一个元素触发,然后您需要逐一暂停迭代其他元素。

举个例子,我是通过属性控件而不是创建一个外部按钮来播放,但是如果你使用自定义按钮,逻辑是一样的。

const tracks = Array.from(document.querySelectorAll('audio'));

tracks.forEach(function(track) {
    track.addEventListener('play', (event) => {
      tracks.forEach(function(track) {
        if(track !== event.target) track.pause();
      })
    })
})
<audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" controls></audio>
<audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" controls></audio>
<audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" controls></audio>
<audio src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3" controls></audio>