尝试在 componentDidMount 中播放音频时出现此错误。 “未捕获( promise )DOMException:play() 失败,因为用户没有先与文档交互。”
componentDidMount() {
document.getElementById("backgroundMusic").play();
}
<audio id="backgroundMusic">
<source src={url} type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
它适用于 onclick 事件。有没有办法在 React 中自动播放音频?我想我可以通过使用 onMouseOver 触发音频开始,但理想情况下,音乐会在没有任何用户交互的情况下开始。
最佳答案
Autoplay Policy Changes不再允许在没有用户交互的情况下自动播放。
- Muted autoplay is always allowed.
- Autoplay with sound is allowed if:
- User has interacted with the domain (click, tap, etc.).
- On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
- The user has added the site to their home screen on mobile or installed the PWA on desktop.
- Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
绕过这个的唯一方法是你的鼠标移动实现
关于javascript - 有没有办法在不使用 onClick 事件的情况下在 React 中自动播放音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65066070/