微信小程序抖音实战-小视频弹幕

如果你去抖音只是为了看小视频就少了一大乐趣,评论区才是最有趣的地方,边看视频边看评论的弹幕是不是更有意思

首先看下效果图

预览效果截图

实现思路

把最新的评论以弹幕的方式展示出来,随机生成字体颜色

局部代码变动

1. 增加一个随机颜色生成算法

function getRandomColor() {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}

解读一下: 
Math.random() * 256 用来获取一个 0 - 256 之间的一个随机数
那为什么要乘以256 呢,那是因为rgb的颜色最大是255
Math.floor 取整数,toString(16) 转为 十六进制的颜色码
color = color.length == 1 ? '0' + color : color 补零操作

2. 视频层开启弹幕

  <video id="myVideo" src="{{videoSrc}}" binderror="videoErrorCallback" autoplay='{{true}}' controls='{{false}}' class='slide-image' loop='true' show-progress='false' show-play-btn='false' show-center-play-btn='true' show-fullscreen-btn='false' objectFit='fill' enable-danmu>

增加了一个 enable-danmu 属性

3. 播放视频增加自动发送弹幕

danmuTimer : null,// 弹幕定时器
  previewSubject: function(){
    var subject = this.data.subject;
    if (subject.type == 'video'){
      // 设置视频地址
      this.setData({
        videoSrc: subject.src,
        isHiddenVideo: false
      })
      // 开始播放
      this.videoContext.play();

      // 自动发送弹幕
      var danMus = [];
      var that = this;
      api.loadTalks({
        data: {
          subjectId: that.data.subject.subjectId,
          page: 1,
          rows: 60
        },
        success: function (page) {
          danMus = page.content;
          // 先播放最新的弹幕, 评论多的话,需要后台数据排序
          danMus.reverse();
          console.log("获取到 " + danMus.length + " 条评论", danMus)
          that.danmuTimer = setInterval(function () {
            var talk = danMus.pop();
            if (talk){
              console.log("发送弹幕: " + talk.content)
              that.videoContext.sendDanmu({
                text: talk.content, // 评论内容
                color: getRandomColor() // 随机颜色
              })
            }else{
              clearInterval(that.danmuTimer);
            }
          }, 1000)
        }
      });

    }else{
      wx.previewImage({
        urls: [subject.coverUrl],
      })
    }
  },

增加一个弹幕定时器变量,在关闭视频的时候使用
在开始播放的后面先请求后台获取评论数据,然后反转一下
为了pop的时候能出来最新的评论,定时每个1秒发送一个评论
当发送完所有评论后关闭定时器

4. 隐藏视频并关闭弹幕

hidePreview: function () {
    var subject = this.data.subject;
    if (subject.type == 'video') {
      // 停止发送弹幕
      clearInterval(this.danmuTimer);
      // 暂停播放
      this.videoContext.pause();
      // 隐藏视频层
      this.setData({
        isHiddenVideo: true
      })
    }
  },

还不赶紧去试试 !!!留下你们的神评论,让更多的同学看到

完整源码请到官网https://100boot.cn的抖音案例下载

 

抖音系列

关注我们

如果需要源码和素材可以关注“IT实战联盟”公*众*号并留言(微商城源码,5个字会收到源码下载地址,一定要看源码里面的操作手册会少走很多弯路),也可以加入交流群和作者互撩哦~~~

猜你喜欢

转载自blog.csdn.net/zhenghhgz/article/details/82218741