创建自定义音频播放器时如何第一时间播放音频?

问题描述 投票:0回答:1

我正在尝试建立一个自定义的音频播放器。虽然这似乎是一个很常见的疑问,但不知道具体的解决方法是什么。

很多浏览器不允许你第一次从javascript中调用play()(阻止自动播放的浏览器),除非用户没有与音频播放按钮交互。但由于我正在用css创建一个自定义的播放器,我所做的就是当用户点击自定义的播放按钮时触发一个事件,然后让javascript调用play()方法。什么是最好的解决方法?

JS Fiddle

似乎在fiddle中运行得很好,但在其他方面得到了以下错误。

Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().
javascript html html5-audio
1个回答
2
投票

// Immediately load the audio in the background. No need to add to DOM
const loadAudio = new Promise(resolve => {
  const audio = new Audio()
  audio.src = 'https://fetch-stream-audio.anthum.com/audio/opus/demo/96kbit.opus'

  // resolve audio as ready to play when we've fetched enough playback bytes
  audio.addEventListener('canplaythrough', () => {
    resolve(audio)
  })
})

async function play() {
  // wait for audio to be ready (loadAudio Promise resolved)
  const audio = await loadAudio

  // restart if already playing
  audio.currentTime = 0

  audio.play()
}

async function stop() {
  const audio = await loadAudio
  audio.pause()
}
button {
  font-size: 18px;
  padding: .5em 1em;
  border: none;
  border: none;
  background: #e9e9e9;
  color: #4c8bf5;
  cursor: pointer;
}
<button class="play" type="button" onclick="play()" title="Play">▶</button>
<button type="button" onclick="stop()" title="Stop">■</button>

另外,考虑使用Opus而不是MP3,以获得更小的、质量更好的文件。

© www.soinside.com 2019 - 2024. All rights reserved.