video 自动播放及循环播放问题

代码

<video id="screenVideo"

       ref="video"

       :muted='muted'

       :src="videoSrc"

       webkit-playsinline="false"

       x-webkit-airplay="allow"

       x5-video-player-type="h5"

       x5-video-player-fullscreen="true"

       x5-video-orientation="portraint"

       style="object-fit:fill">

</video>

 

代码关于video

  -> muted: true/false 静音

 

  -> webkit-playsinline : ios 10中设置可以让视频在小窗内播放,即非全屏播放

 

  -> x-webkit-airplay :landscape|portrait 播放器显示的方向,横屏|竖屏,默认值为竖屏,该属性只有在设置【x5-video-player-type="h5"】之后才生效

 

  -> x5-video-player-type="h5" :  启用x5内核H5播放器

 

  -> x5-video-player-fullscreen="true" : 全屏设置,设置为 true 是防止横屏

 

  -> style="object-fit:fill" : 加这个style会让 Android / web 的视频在微信里的视频全屏,如果是在手机上预览,会让视频的封面同视频一样大小

 

video自动播放问题

报错 一 :

   场景: 视频较大时,无法自动播放。已设置loop属性,但依然无法自动播放。

 

   chrome报错Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. https://goo.gl/xX8pDD

 

   safari报错:NotAllowedError: The request is not allowed by the user agent or the platform in the current context, possibly because the user denied permission.

 

  原因:chrome66版本新增的特性,为了避免标签产生随机噪音,不支持无用户交互状态下自动播放,即:禁止自动播放。

     Chrome在18年4月做了更改,浏览器为了提高用户体验,减少数据消耗,现在都在遵循autoplay政策。

   1).muted autoplay始终被允许

       2).音乐的autoplay 只有在下面集中情况下起作用:

          2.1). 有用户行为发生像(click,tap,etc);

          2.2). 对于桌面程序,用户已经提前播放了音频;

           2.3对于移动端用户将音频网址home screen;

  以上,将loop循环播放以及autoplay更改为手动设置。代码如下:

 

/*
* 手动监听视频播放结束
* */
let screenVideo = document.getElementById('screenVideo')
screenVideo && (this.muted = false)
screenVideo && (screenVideo.addEventListener('ended', function () {
screenVideo.play && screenVideo.play()
}))

注意:video不能带loop属性,否则监听不到ended事件 。

然而,去掉autoplay和loop属性更改为手动配置,且设置为静音模式muted为true,依然不能实现循环播放。播放结束后,页面再次报错。

报错 二 :

  1. Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().报了一个promise的错,play操作被pause操作暂停。

      2. Uncaught (in promise) DOMException: The element has no supported sources.

以及【eruda】报的错。

 

查了原因,音频文件还未被加载完成。那么既然play返回promise实例。我们可以在 play() 执行成功后,播放音频,然后执行后续操作。

更改代码如下:

    window.addEventListener('load', function () {
var screenVideo = document.getElementById('screenVideo')
screenVideo.addEventListener('ended', function () {
screenVideo.load();
let playPromise = screenVideo.play();
if (playPromise !== undefined) {
playPromise.then(() => {
screenVideo.play()
}).catch(() => {
console.log('catch');
})
}
}, false);
})

至此成功!
===========番外篇=============
window.addEventListener('load', function () {
var screenVideo = document.getElementById('screenVideo')
screenVideo.addEventListener('ended', function () {
screenVideo.pause()
screenVideo.load()
screenVideo.play()
}, false);
})
以上也可实现,但是未找到理论依据......





一点一滴累积,总有一天你也会成为别人口中的大牛!
原文地址:https://www.cnblogs.com/fancyLee/p/12012196.html