uni-app实现小程序上下滑动播放视频
实现代码
您可以通过以下步骤实现在uni-app小程序中上下滑动播放视频:
1.在页面中引入video组件,并设置宽高及src属性。
<video src="../video.mp4" id="video" style="width: 100%; height: 100%;" />
2.在页面的onLoad生命周期方法中获取video组件并添加上下滑动事件。
onLoad() {
const video = uni.createVideoContext('video')
let startY
video.onTouchStart = function(e) {
startY = e.touches[0].clientY
}
video.onTouchEnd = function(e) {
const endY = e.changedTouches[0].clientY
if (endY - startY > 100) {
video.playbackRate(1.5)
video.play()
} else if (startY - endY > 100) {
video.pause()
}
}
}
3.在上下滑动事件中获取触摸开始和结束的Y坐标,并根据Y坐标的差值控制视频的播放和暂停。
onReady() {
this.videoContext = uni.createVideoContext("myVideo",this)
},
methods:{
playVideo(){
this.videoContext.seek(0)
this.videoContext.play()
console.log("播放视频");
},
pauseVideo(){
this.videoContext.pause()()
console.log("暂停视频");
}
}
下面要做的就是解决如何让父组件调用子组件的方法,修改 videoList.vue,给其中的 videoPlayer 增加 ref
<videoPlayer ref="player" :video="item"></videoPlayer>
然后通过 this.$refs.player 可以找到 videoPlayer 这个插件,由于是个数组,所以通过 page 来找到当前页。当第一个视频滑动到第二个视频,第一个视频应该暂停,第二个应该自动播放,也就是上滑的情况。下滑的情况则相反,因此完善代码:
data() {
return {
page:0
};
},
methods: {
change(res) {
clearTimeout(time)
this.page = res.detail.current
time = setTimeout(() => {
if (this.pageStartY > this.pageEndY) {
console.log("向上滑动"+this.page);
this.$refs.player[this.page].playVideo()
this.$refs.player[this.page-1].pauseVideo()
this.pageStartY = 0
this.pageEndY = 0
} else {
console.log("向下滑动"+this.page);
this.$refs.player[this.page].playVideo()
this.$refs.player[this.page+1].pauseVideo()
this.pageStartY = 0
this.pageEndY = 0
}
},1)
},
},
增加双击点赞功能
data() {
return {
dblClick: false
};
},
methods: {
click() {
clearTimeout()
this.dblClick = !this.dblClick
timer = setTimeout(() => {
//300ms之内dblClick为true为单击
if (this.dblClick) {
//单击
if (this.play === false) {
this.playthis()
} else {
this.pauseVideo()
}
} else {
//双击
this.$emit("doubleClick")
}
this.dblClick = false
}, 300)
},
}
4.如果向下滑动距离大于100px,将视频的播放速率设置为1.5倍,并播放视频;如果向上滑动距离大于100px,暂停视频。
这样就可以在uni-app小程序中实现上下滑动播放视频的功能了。
源码获取方法:
需要完整源码的朋友,希望你能点赞+收藏+评论,然后私信我即可~
会员学习群:
可添加学习会员小助手咨询(微信:mifankeji77)