音频确实在第一次加载时播放,但在页面刷新时出现以下错误:
未捕获(promise中)DomeException:play()失败,因为用户没有首先与文档交互。
Html:
<div>
<audio src="./songs/the_end.mp3" id="theEnd"></audio>
</div>
JS:
const theEnd = document.querySelector('#theEnd')
window.addEventListener('load', () => {
theEnd.play()
})
我应该做什么更改,以便音频在页面刷新时播放,就像第一次加载时一样?
Codesandbox供你们测试:https://codesandbox.io/s/fervent-brook-l06u8
您可以尝试添加autoplay
属性。
因此:
<div>
<audio autoplay src="./songs/the_end.mp3" id="theEnd"></audio>
</div>