谷歌浏览器 video 元素设置 autoplay
,我们原意是希望页面加载时自动播放,但实际上并没有自动播放,在控制台报错如下:
Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.
这里的意思是,是因为用户没有先和网页交互所以播放失败。
首先去谷歌开发者文档查询下此类报错原因:
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.
挑重点说,其实就是怕自动播放声音干扰到正常用户。
Muted
静音的自动播放是被允许的。在不考虑其他终端运行时可以修改浏览器设置的自动播放权限:
No user gesture is required
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>
AudioContext 接口表示由链接在一起的音频模块构建的音频处理图,逻辑我就不贴了,懒。