uniapp video 如何限制播放时长
在uniapp中使用video组件时,如何限制视频的播放时长?比如只允许用户观看前30秒的内容,后面的部分自动停止播放。需要监听哪些事件或设置哪些属性来实现这个功能?求具体的代码实现方案。
2 回复
在uniapp中,可以通过监听视频的timeupdate事件,获取当前播放时间。当超过设定时长时,调用videoContext.seek()跳转到指定位置或暂停播放。
在 UniApp 中,可以通过以下方法限制 video 组件的播放时长:
方法一:使用 @timeupdate 事件监听播放进度
<template>
<video
:src="videoSrc"
@timeupdate="onTimeUpdate"
controls
></video>
</template>
<script>
export default {
data() {
return {
videoSrc: '/static/video.mp4',
maxDuration: 60 // 限制最大播放时长60秒
}
},
methods: {
onTimeUpdate(e) {
const currentTime = e.detail.currentTime
if (currentTime >= this.maxDuration) {
// 暂停播放
this.$refs.video.pause()
// 可选:跳回起始位置
this.$refs.video.seek(0)
}
}
}
}
</script>
方法二:使用 setInterval 定时检查
<template>
<video
ref="video"
:src="videoSrc"
@play="startCheck"
@pause="stopCheck"
></video>
</template>
<script>
export default {
data() {
return {
videoSrc: '/static/video.mp4',
maxDuration: 60,
timer: null
}
},
methods: {
startCheck() {
this.timer = setInterval(() => {
const videoContext = uni.createVideoContext('myVideo', this)
videoContext.getCurrentTime().then(time => {
if (time >= this.maxDuration) {
videoContext.pause()
videoContext.seek(0)
this.stopCheck()
}
})
}, 1000)
},
stopCheck() {
if (this.timer) {
clearInterval(this.timer)
this.timer = null
}
}
}
}
</script>
注意事项:
- 方法一更推荐,性能更好
- 记得给 video 组件添加 ref 属性以便获取实例
- 可根据需求调整最大时长和限制后的行为(暂停/跳转等)
- 在 H5 端和小程序端均可正常使用
通过以上方法即可有效限制视频播放时长。

