2. chrome自动播放问题
(1) 背景和问题
比较明确的是在mobile中,iOS不允许自动播放,但是安卓是可以的。为了兼容性,一般采用的是点击播放按钮播放,或者首次触屏后开始播放。
然而最近遇到的问题:在chrome浏览器中页面加载完成之后播放视频会失败,并且出现如下报错:
(2) chrome条款
上图中的链接为:https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
了解到在2018年4月Google出台了关于Chrome自动播放的限制,如下:
- 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.
(3) 解决方案
[1] 几种解决方式
- 静音播放
针对网页中比较常见的video作为background的情况,并不希望用户感受到这是个视频或者去点击播放按钮。所以,最简便的方法是将视频直接静音,保证其能自动播放。
<video id="video" muted autoplay src="">
- 静音播放,提供关闭静音按钮
先将视频静音保证其开始播放,在视频上增加按钮,用户可以点击取消静音。
<button id="unmute" onClick="document.getElementById('video').muted = false;"></button>
- 不自动播放,提供播放按钮
对于不希望静音的视频,可以显示播放按钮,用户点击播放按钮后再进行播放。
[2] 代码实现
可以通过play方法返回的Promise(什么是Promise?)判断是否播放被禁止了。如果禁止了,静音后再播放或者显示播放按钮。
var mp4 = document.getElementById('video');
var promise = mp4.play();
if (promise !== undefined) {
promise.then(function(){
// Autoplay started!
}).catch(function() {
// Autoplay was prevented.
//--静音再播放--
mp4.muted=true;
mp4.play();
//--显示播放按钮--
//show a "Play" button so that user can start playback.
});
}