首先video组件定义如下:
<video
id="videoRef"
:src="videoSrc"
@timeupdate="onTimeUpdate"
/>
1、监听视频快进。自带的video组件没有相关参数直接去禁用,如下方式是通过记录上一次的播放时间,用当前时间-上次播放时间,如果间隔大于1,可鞥是就在快进了,通过seek方法还原到上次的播放时间。如果想隐藏video上的进度条的话 可以通过css 将透明度降为0,最好不要直接 隐藏,否则开始和结束时间会显示在一起,展示效果不大好;
const playedTime = ref<number>(0)
const videoContext = ref()
videoContext.value = uni.createVideoContext('videoRef');
function onTimeUpdate(e: any) {
if(e.detail.currentTime-playedTime.value > 1){
// 禁止拖动进度条快进
uni.showToast({
title: '不能快进哦',
icon: 'none',
});
videoContext.value.seek(playedTime.value)
return;
}
playedTime.value = e.detail.currentTime
}
2、监听倍速播放有尝试了两种方式:
方法一:类似快进的方式,处理记录上一次的播放时间,还需要加一个变量记录上一次播放的时间戳:const playedTimestamp = ref<number>(0)
同样是在 【onTimeUpdate】方法里面 通过实时获取当前的时间戳和当前时间 与上一次的时间进行比对,可以大概计算倍速比例,但是有些许误差:
function handleTimeUpdate(e: any) {
// 判断倍速播放
const currentTime = e.detail.currentTime
const now = Date.now()
if (playedTime.value > 0 && playedTimestamp.value > 0) {
const timeDiff = (now - playedTimestamp.value) / 1000 // 秒
const videoDiff = currentTime - playedTime.value
const rate = videoDiff / timeDiff
console.log(`估算播放速率 2: ${rate.toFixed(2)}x`)
if (rate > 1.2) {
uni.showToast({ title: '检测到倍速播放', icon: 'none' })
// 可选:回退进度
videoContext.value.seek(playedTime.value)
return;
}
}
playedTimestamp.value = now
playedTime.value = currentTime;
}
方法二:通过原生<video />的标签属性 【playbackRate】,直接获取视频倍速。
优点:数据比较准确,设置的是多少就是多少
缺点:可能有兼容问题;目前测google、edge没问题;
function handleTimeUpdate(e: any) {
uni.createSelectorQuery()
.select('#videoRef')
.fields({ node: true, size: false })
.exec((res) => {
const videoElement = res[0]?.node;
if (videoElement) {
const rate = videoElement.playbackRate;
console.log('播放速率:', rate);
if (rate > 1.0) {
uni.showToast({ title: '不能倍速倍速播放哟', icon: 'none' });
videoElement.currentTime = playedTime.value;
}else{
playedTime.value = e.detail.currentTime
}
}
});
}
最后:
如果大家有更好的处理方式,欢迎留言哟