CustomVideo.js 3.14 KB
// pages/crowdfunding/components/CustomVideo/CustomVideo.js
Component({
  options: {
    styleIsolation: 'shared'
  },
  /**
   * 组件的属性列表
   */
  properties: {
    playConf: {
      type: Object,
      value: () => { }
    },
    fileList: {
      type: Array,
      value: []
    },
    // 全屏
    videoFullscreen: {
      type: Boolean,
      value: false
    },
    // 购买按钮
    isAction: {
      type: Boolean,
      value: false
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    sliderValue: 0, //控制进度条slider的值,
    updateState: false, //防止视频播放过程中导致的拖拽失效
    playStates: true, //控制播放 & 暂停按钮的显示,
    videoTime: {
      total: '',
      current: ''
    },
    fileIdx: 0
  },

  lifetimes: {
    attached() {
      this.setData({
        videoContext: wx.createVideoContext('video-player', this),
        updateState: true
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    // 时间补0
    addZero(i) {
      return i < 10 ? `0${i}` : `${i}`;
    },
    formatDuration(duration) {
      duration = parseInt(duration || 0)
      const hour = this.addZero(parseInt(duration / 3600))
      const minute = this.addZero(parseInt(duration % 3600 / 60))
      const sec = this.addZero(parseInt(duration % 60))
      return (hour ? hour + ':' : '') + minute + ":" + sec
    },
    // 视频加载完成
    videoLoaded(e) {
      this.setData({
        ['videoTime.total']: this.formatDuration(e.detail.duration)
      })
    },
    // 视频播放结束
    videoEnd(e) {
      this.data.videoContext.play()
      if(this.data.fileList.length == 1) {
        this.setData({
          sliderValue: 0
        })
        return true
      }
      this.setData({
        sliderValue: 0,
        ['videoTime.total']: this.formatDuration(e.detail.duration),
        fileIdx: this.data.fileIdx == (this.data.fileList.length - 1) ? 0 : this.data.fileIdx + 1
      })
    },
    // 播放进度变化时触发
    videoUpdate(e) {
      if (this.data.updateState) { //判断拖拽完成后才触发更新,避免拖拽失效
        let sliderValue = e.detail.currentTime / e.detail.duration * 100
        this.setData({
          sliderValue,
          duration: e.detail.duration,
          ['videoTime.current']: this.formatDuration(e.detail.currentTime)
        })
      }
    },
    // 拖动slider
    sliderChanging(e) {
      this.setData({
        updateState: false //拖拽过程中,不允许更新进度条
      })
    },
    sliderChange(e) {
      if (this.data.duration) {
        this.data.videoContext.seek(e.detail.value / 100 * this.data.duration); //完成拖动后,计算对应时间并跳转到指定位置
        this.setData({
          sliderValue: e.detail.value,
          updateState: true, //完成拖动后允许更新滚动条
          ['videoTime.current']: this.formatDuration(e.detail.currentTime)
        })
      }
    },
    // 播放/暂停
    handlePlayPause() {
      this.data.playStates ? this.data.videoContext.pause() : this.data.videoContext.play()
      this.setData({
        playStates: !this.data.playStates
      })
    },
  }
})