我们要的是只允许同时播放一个视频
网上的很多方法只适用于h5(浏览器)打包就不行了。
一句话:除当前操作的视频外全部 pause()
app和h5通用版(建议复制黏贴html代码 )亲测有效!!! 重点在于:id 和:data-id
html:
<video :src="item.picUrl" @play="playing" :data-id="item.broadcastId" :key="item.broadcastId" :autoplay='true' @timeupdate='timeupdate' :id="'video'+item.broadcastId" controls webkit-playsinline playsinline x5-video-player-type="h5" x5-video-orientation="portraint"></video>
js:
playing(e) {
let currentId = 'video' + e.currentTarget.dataset.id;// 获取当前视频id
console.log("currentId", currentId);
this.videoContent = uni.createVideoContext(currentId);
console.log("this.videoContent", this.videoContent)
let trailer = this.fwList;
trailer.forEach(function(item, index) { // 获取json对象并遍历, 停止非当前视频
if (item.template==5) {
let temp = 'video' + item.broadcastId;
if (temp != currentId) {
console.log(temp);
uni.createVideoContext(temp).pause(); //暂停视频播放事件
}
}
})
},
h5版
html:
<video :src="item.picUrl" @play="playVideo" :id="'video'+item.broadcastId" :poster="item.picUrl" controls :show-center-play-btn="false" auto-pause-if-navigate></video>
js:
playVideo (e) {
//获取自定义的id值
let currentId = e.currentTarget.id;
// 创建视频实例
this.videoContent = uni.createVideoContext(currentId, this)
// 遍历数组 我这里template为5时是视频
this.fwList.forEach((item,index)=>{
if(item.template==5) {
//获取视频的id
let tempId = 'video'+item.broadcastId
// 与当前选择的id作比较 如果不是全部暂停
if(tempId!=currentId) {
uni.createVideoContext(tempId, this).pause()
}
}
})
},
获取视频第一帧
自动播放,监听播放大于0.2s时,循环咱暂停
js:
// 播放进度变化时触发
timeupdate(e) {
console.log(e)
if (this.isInit&&e.detail.currentTime > 0.2) { //判断播放大于0秒
this.isInit = false //初始化
let trailer = this.fwList;
trailer.forEach(function(item, index) { // 获取对象并遍历, 停止非当前视频
if (item.template==5) {
let temp = 'video' + item.broadcastId;
console.log(temp);
uni.createVideoContext(temp).pause(); //暂停视频播放事件
}
})
}
},
最后别忘记了关闭当前页面时关闭video
onHide() {
if(this.videoContent) {
this.videoContent.pause()
}
},