绿满眶商城微信小程序-uniapp
xiangpei
2025-05-27 8e003d317da31c555c5c746f62bd74c8dd46638b
视频播放记录完善
1个文件已修改
34 ■■■■■ 已修改文件
pages/tabbar/index/home.vue 34 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pages/tabbar/index/home.vue
@@ -101,6 +101,10 @@
export default {
  data() {
    return {
        startHidenTime: 0, // 记录切换至其它页面的时间,用于计算视频观看时间减去的部分
        totalHidenTime: 0, // 总共隐藏页面的时间
        startPauseTime: 0, // 开始暂停的时间
        totalPauseTime: 0, // 总共暂停的时间
        playRecord: {
            videoId: null,
            viewDuration: 0, // 这个视频总共观看了多久
@@ -121,7 +125,14 @@
    }
  },
  onShow() {
    // this.loadVideos();
      // 如果视频按下暂停后切换页面再回到页面时,只算暂停时间(因为暂停时间和离开页面时间是重复的,只算一个)
      if(this.startHidenTime !== 0 && this.currentVideoIsPlaying) {
          const duration = Date.now() - this.startHidenTime
          this.totalHidenTime += duration
      }
  },
  onHide() {
      this.startHidenTime = Date.now()
  },
  onLoad() {
      this.loadVideos();
@@ -162,6 +173,13 @@
    
    // 滑动切换视频
    onSwiperChange(e) {
        // 如果视频处于暂停状态往下刷视频,那么需要再计算一次暂停时间
        if(!this.currentVideoIsPlaying) {
            if(this.startPauseTime !== 0) {
                const duration = Date.now() - this.startPauseTime
                this.totalPauseTime += duration
            }
        }
        // 保存上一个视频的播放记录
        this.savePlayRecord()
        const oldIndex = this.currentIndex;
@@ -172,7 +190,8 @@
        if (this.videoContexts[oldIndex]) {
            this.videoContexts[oldIndex].pause();
        }
        this.currentVideoIsPlaying = true;
        this.startPauseTime = 0;
        // 播放当前视频
        if (this.videoContexts[this.currentIndex]) {
            this.videoContexts[this.currentIndex].play();
@@ -217,11 +236,16 @@
        if(this.playRecord.startPlayTime === 0) {
            this.playRecord.startPlayTime = Date.now();
        }
        if(this.startPauseTime !== 0) {
            const duration = Date.now() - this.startPauseTime
            this.totalPauseTime += duration
        }
    },
    
    // 视频暂停事件
    onPause(index) {
      this.currentVideoIsPlaying = false;
      this.startPauseTime = Date.now()
    },
    
    // 视频结束事件
@@ -236,9 +260,11 @@
    
    // 保存播放记录
    async savePlayRecord() {
        console.log(Date.now(), this.playRecord.startPlayTime, this.totalHidenTime);
        const data = {
            videoId: this.playRecord.videoId,
            viewDuration: Date.now() - this.playRecord.startPlayTime,
            viewDuration: Date.now() - this.playRecord.startPlayTime - this.totalHidenTime - this.totalPauseTime,
            playAt: this.playRecord.playAt
        }
        this.playRecord = {
@@ -247,6 +273,8 @@
            playAt: 0 ,// 这个视频播放到哪了
            startPlayTime: 0 // 这个视频从什么时候开始播放的
        }
        this.totalHidenTime = 0
        this.totalPauseTime = 0
        savePlayRecord(data)
    }
  }