demo
need
There are many videos playing on a page at the same time. When the user clicks a video, the video starts to play. When another video is clicked, the previous video is paused, so that only one video is playing on the current page.
principle
When playing a video, first judge whether there is a video currently playing, if not, play it, if so, pause other videos, and then play the current video
source code
wxml
<view wx:for="{
{videos}}" class="recordItem_hot" wx:key="{
{index}}" data-item='{
{item}}'>
<video class="cover_img" src="{
{item.url}}" objectFit="cover" show-fullscreen-btn id="video{
{index}}" bindtap="video_play" />
<view class="hot_name">
<view class="name_view">{
{item.title}}</view>
</view>
</view>
js
Page({
/**
* 页面的初始数据
*/
data: {
videos:[
{
url:'https://scenicpicture.umituo.com/upload/video/0387064bad8464868ae292c8cb793f86.mp4',
title:'视频一'
},
{
url:'https://scenicpicture.umituo.com/upload/video/ec341fa007ce6943ed997f5b079ea44b.mp4',
title:'视频二'
},
{
url:'https://scenicpicture.umituo.com/upload/video/mmexport1645779520102.mp4',
title:'视频三'
},
],
indexCurrent: null,
},
video_play(e) {
let curIdx = e.currentTarget.id;
// 没有播放时播放视频
// console.log(curIdx)
if (!this.data.indexCurrent) {
this.setData({
indexCurrent: curIdx
})
let videoContext = wx.createVideoContext(curIdx,this) //这里对应的视频id
videoContext.play()
} else { // 有播放时先将prev暂停,再播放当前点击的current
let videoContextPrev = wx.createVideoContext(this.data.indexCurrent,this)//this是在自定义组件下,当前组件实例的this,以操作组件内 video 组件(在自定义组件中药加上this,如果是普通页面即不需要加)
if (this.data.indexCurrent != curIdx) {
console.log(123)
videoContextPrev.pause()
this.setData({
indexCurrent: curIdx
})
let videoContextCurrent = wx.createVideoContext(curIdx,this)
videoContextCurrent.play()
}
}
},
})