javascript - 有没有办法在不使用 onClick 事件的情况下在 React 中自动播放音频?

标签 javascript reactjs

尝试在 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/

相关文章:

javascript - JS循环遍历表格并根据条件在列中打印文本

变量中的 JavaScript 函数

Javascript - 检测第一个字符并提醒用户

javascript - React 元素类型无效

html - 如何在ReactJS中的图像上添加文本?

asp.net - 使用 Ajax,是在服务器端还是在客户端生成额外的标记更好?

javascript - 如何使用 Javascript 判断 HTML 属性是否存在

javascript - 从不希望我拥有它的组件获取鼠标移动事件

javascript - 在 Chrome 中使用 React 添加新的 DOM 项目不会保持预期的滚动位置

javascript - react : Instantiate component once and use multiple times