uniapp video组件如何监听视频快进或倍速播放

首先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
          }
        }
      });
}

最后:

如果大家有更好的处理方式,欢迎留言哟

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值