【问题标题】:Multiple Audio elements interfering on the same page多个音频元素干扰同一页面
【发布时间】:2022-01-16 18:30:17
【问题描述】:

我有一个带有多个音频气泡的 web 应用,但播放一个音频气泡会播放来自不正确音频气泡的音频。我正在使用:this.audio = new Audio(url)。他们以某种方式干扰。如何解决?

【问题讨论】:

    标签: javascript html5-audio web-audio-api


    【解决方案1】:

    确保所有音频对象都可以相互访问,并在开始之前暂停它们。

    const audioPromises = [
      audioFromUrl('https://opus-bitrates.anthum.com/audio/hyper/music-96.opus'), 
      audioFromUrl('https://opus-bitrates.anthum.com/audio/music-96.opus'),
    ]
    
    document.querySelectorAll('.play').forEach(el => el.addEventListener('click', () => {
      play(parseInt(el.dataset.idx))
    }))
    
    document.querySelectorAll('.stop').forEach(el => el.addEventListener('click', stopAll))
    
    async function play(idx) {
      const audio = await audioPromises[idx]
      await stopAll()
      audio.play()
    }
    
    function stopAll() {
      return Promise.all(audioPromises)
        .then(audios => audios.map(audio => audio.pause()))
    }
    
    
    async function audioFromUrl(url) {
      const arrayBuffer = await (await fetch(url)).arrayBuffer()
      const audio = new Audio()
      audio.src = URL.createObjectURL(
        new Blob([arrayBuffer])
      )
      return audio
    }
    <button class="play" data-idx="0">Play 1</button>
    <button class="play" data-idx="1">Play 2</button>
    <br /><br />
    <button class="stop" data-idx="1">Stop All</button>

    【讨论】:

      猜你喜欢
      • 2014-12-11
      • 2013-03-04
      • 1970-01-01
      • 2022-01-23
      • 2021-06-02
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多