1. 问题

谷歌浏览器 video 元素设置 autoplay,我们原意是希望页面加载时自动播放,但实际上并没有自动播放,在控制台报错如下:
Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.
这里的意思是,是因为用户没有先和网页交互所以播放失败。

2. 解析

首先去谷歌开发者文档查询下此类报错原因:

Autoplay Policy
Changes Chrome’s autoplay policies are simple:

  • 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 play video with sound.
    • On mobile, the user has added the site to his or her home screen.
  • Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.

挑重点说,其实就是怕自动播放声音干扰到正常用户。

  1. Muted静音的自动播放是被允许的。
  2. 声音播放在以下几类中被允许:
    1. 用户和文档发生交互交互后,比如点击、触摸事件等。
    2. PC端在谷歌类浏览器设置的自动播放权限中设置允许自动播放。
    3. 移动端用户将站点作为首屏页面。
  3. frames内框分发自动播放权限给frames子内框。

3. 处理方案

1. 改浏览器自动播放权限

在不考虑其他终端运行时可以修改浏览器设置的自动播放权限:

  1. 在chrome浏览器中输入:chrome://flags/#autoplay-policy。
  2. Autoplay policy中将 Default 改为 No user gesture is required
  3. 重启Chrome。
    该方案最新的浏览器未找到,朋友们可以指正我的错误

2. 设置video标签属性muted静音,通过后续交互放开声音

muted 属性用于表示媒体元素是否静音。

<!--先在元素上分别设置自动播放和静音-->
<video id="video" src="/assets/video/1.mp4" autoplay muted />

<button id="btn" >播放声音</button>

<script>
const videoDom = document.getElementById('video');
const btnDom = document.getElementById('btn');

//	点击之后允许播放声音
btnDom.addEventListener('click', () => {
	videoDom.muted = false;
})
</script>

3. 使用AudioContext创建的对象自动播放(谷歌声音仍然受限)

AudioContext 接口表示由链接在一起的音频模块构建的音频处理图,逻辑我就不贴了,懒。

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐