小程序多视频暂停播放,超出可视区域暂停播放
示例是用uni-app写的,微信和其他小程序参照下。
一、多视频暂停播放
- 思路
构建两个view,一个封面图片模拟层,一个video默认隐藏。
当点击封面时候,隐藏封面,显示视频,停止上个视频,播放当前点击视频
- 样式 (只显示主要代码)
<view class="video_list y-f" :id="'el' + item.id">//这个id后面用来控制超出可视区域停止播放
<view class="video">//视频层data中playVideoId默认为unll。
<video
v-if="playVideoId == item.id"
:id="'vid' + item.id"
class="video-context"
show-fullscreen-btn
autoplay
controls
:src="item.videoPath"
:poster="item.coverImg"
></video>
<view v-else class="" @tap="videoPlay(item.id)"> //封面图片层
<view class="i_box"><image class="video_img" :src="item.coverImg" mode="widthFix"></image></view>
<view class="video_logo cuIcon-playfill"></view>
</view>
</view>
</view>
- js
// 视频控制播放
videoPlay(id) {
if (!this.playVideoId) {//playVideoId为默认值null
this.playVideoId = id;
let videoContext = uni.createVideoContext('vid' + id); //获取当前视频实例。
videoContext.play();
} else {//playVideoId为默认值为上个视频id.
let videoContextPrev = uni.createVideoContext('vid' + this.playVideoId);//获取上个视频实例
if (this.playVideoId != id) {
videoContextPrev.stop();
} else {
videoContextPrev.play();
}
this.playVideoId = id;
let videoContextCurrent = uni.createVideoContext('vid' + id);
videoContextCurrent.play();
}
},
二、超出滚动区域停止播放
- 思路
知道播放视频距离可视区域高度,滚动的时候实时监控。
- 样式跟上面一样,直接贴js
onPageScroll(e) {//滚动监听生命周期函数
let query = uni.createSelectorQuery();//查询,组件中加上.in(this),不然获取不到。
let wh = uni.getSystemInfoSync().windowHeight;//可视区域高度
if (this.playVideoId) {
const id = this.playVideoId;
query
.select('#el' + id)
.boundingClientRect(rect => { // 我查询的是包裹视频的元素,可根据需求
let top = rect.top;//距离顶部高度
let bottom = rect.bottom;
let vh = rect.height;//元素高度
if (top < 0 || bottom > (vh+wh) { //当视频距离顶部为零,测了下,这个为0,视频不可见。
this.playVideoId = null;
}
})
.exec();
}
},
基本实现如上,有其他问题和想法可以评论。