文章举报预留地

小程序实现观看视频领红包功能

2021-02-20  本文已影响0人  变量只提升声明不提升赋值

前言:
项目是一个基于taro开发的小程序,客户要求实现一个观看视频领红包的功能,要求视频暂停则停止计时,重复播放同一个视频也停止计时。也就是要不停的刷视频才能累计时常解锁红包。

思路:
通过定时器来完成,给每个视频的数据添加一个观看与否的字段。未观看为false,看了为true。然后去监听video标签的播放事件,暂停事件。以及播放完成事件。 播放的时候启动定时器,暂停就删除定时器。播放完成后字段改为true。启动定时器前判断这个字段是否为false,为false才去启动定时器。

<Video 
custom-cache={false} 
onPause={() => store.stopTime(item, index)} 
onEnded={() => store.endTime(item, index)} 
onPlay={() => store.timePlay(item, index)} 
id={`myVideo${index}`} 
src={item.video_url[0].url} controls={true} 
show-fullscreen-btn={false} loop={true} 
className={styles.video} >
</Video>

onPause,onEnded,onPlay三个api分别是暂停,结束,开始这三个状态会触发的函数。

  /**
   * 红包功能需要用到的相关变量
   * totalTime  观看视频的时间
   * TimeoutId 定时器id
   * lookNum  观看视频的个数
   * jindunei 内部进度条
   * whatchTime 领取红包需要看多长时间
   * integral 积分数量
   * redCount 领取的第几个红包
   * whatTimeList 观看时长数组
   * jifenopen 领取红包的提示
   */
  @observable hongbaoopen = false
  whatTimeList = [60, 60 * 2, 60 * 3, 60 * 4, 60 * 5, 60 * 6, 60 * 7, 60 * 8, 60 * 9, 60 * 10]
  @observable redCount = 0
  @observable integral = 0
  @observable jindunei = 0
  lookNum = 0
  TimeoutId = null
  totalTime = 0
//视频播放结束触发的方法。
endTime = (item, index) => {
    item.looks = true
    this.stopTime()
  }

//视频播放触发的方法
timePlay = (item, index) => {
    if (this.redCount < 10) {
      let count = 100 / this.whatTimeList[this.redCount]
      if (!item.looks) {
        clearInterval(this.TimeoutId)
        this.TimeoutId = setInterval(() => {
          this.totalTime++
          if (this.jindunei < 100) {
            this.jindunei += count
          }
          if (this.totalTime == this.whatTimeList[this.redCount]) {
            this.totalTime = 0
            this.jindunei = 0
            if (this.redCount < 10) {
              this.getRedbao(1)
            }
          }
          console.log(this.totalTime, this.jindunei)
        }, 1000)
      }
    }
  }

//视频暂停触发的方法
  stopTime = (item, e) => {
    if (this.TimeoutId) {
      clearInterval(this.TimeoutId)
      this.TimeoutId = null
      console.log(this.totalTime, 'stop')
    }
  }

在真机中,上下滑动切换视频时有时候会出现暂停的监听方法失效的问题。所以要在播放的方法里也去删除一次定时器。以防万一。

在播放的方法里就是启动定时器改变进度条

上一篇 下一篇

猜你喜欢

热点阅读