不大方便展示视频哈~~

在这里插入图片描述

<!--pages/contact/contact.wxml-->

<view>
  <view class="live-box">
    <video id="myVideo" class="live-video" controls src="我用的是直播回放,由于微信小程序的直播暂时只支持商家的" enable-danmu danmu-btn></video>
  </view>
  <view class="sc">
    <scroll-view scroll-y scroll-into-view='{{toView}}' >
  <!-- <view class='scrollMsg'> -->
  <block wx:key="keys" wx:for='{{msgList}}' wx:for-index="index" >

    <!-- 单个消息1 客服发出(左) -->
    <view wx:if='{{item.style=="bubble you"}}' id='msg-{{index}}' style='display: flex; padding: 3vw 11vw 2vw 2vw;'>
      <view style='width: 11vw; height: 11vw;'>
        <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1031084171,3750714591&fm=26&gp=0.jpg'></image>
      </view>
      <view style='width: 4vw; height: 11vw; margin-left: 0.5vw; display: flex; align-items: center; z-index: 9;'>
      </view>
      <view class='leftMsg'>{{item.data}}</view>
    </view>

    <!-- 单个消息2 用户发出(右) -->
    <view wx:else id='msg-{{index}}' style='display: flex; justify-content: flex-end; padding: 2vw 2vw 2vw 11vw;'>
      <view class='rightMsg'>{{item.data}}</view>
      <view style='width: 4vw; height: 11vw; margin-right: 0.5vw; display: flex; align-items: center; z-index: 9;'>
      </view>
      <view style='width: 11vw; height: 11vw;'>
        <image style='width: 11vw; height: 11vw; border-radius: 10rpx;' src='https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=1031084171,3750714591&fm=26&gp=0.jpg'></image>
      </view>
    </view>

  </block>
  <!-- </view> -->

  <!-- 占位 -->
  <view style='width: 100%; height: 18vw;'></view>
</scroll-view>

<view class='inputRoom' style='bottom: {{inputBottom}}'>
  <!-- <image style='width: 7vw; margin-left: 3.2vw;' src='' mode='widthFix'></image> -->
  <input bindconfirm='sendClick' adjust-position='{{false}}' value='{{inputVal}}' confirm-type='send' bindfocus='focus' bindblur='blur'  bindinput="getDanmu"></input>
  
  <view class="button" bindtap="sendDanmu">发送弹幕</view>
</view>
</view>
  </view>


wxss

/* pages/live/live.wxss */
page {
  background-color: #f1f1f1;
}

.inputRoom {
  width: 100vw;
  height: 16vw;
  border-top: 1px solid #cdcdcd;
  background-color: #f1f1f1;
  position: fixed;
  bottom: 0;
  display: flex;
  align-items: center;
  z-index: 20;
}

input {
  width: 76vw;
  height: 9.33vw;
  background-color: #fff;
  border-radius: 40rpx;
  margin-left: 2vw;
  padding: 0 3vw;
  font-size: 28rpx;
  color: #444;
}

.leftMsg {
  font-size: 35rpx;
  color: #444;
  line-height: 7vw;
  padding: 2vw 2.5vw;
  background-color: #fff;
  margin-left: -1.6vw;
  border-radius: 10rpx;
  z-index: 10;
}

.rightMsg {
  font-size: 35rpx;
  color: #444;
  line-height: 7vw;
  padding: 2vw 2.5vw;
  background-color: #96EB6A;
  margin-right: -1.6vw;
  border-radius: 10rpx;
  z-index: 10;
}

.live-box {
  width: 100%;
  height: 400rpx;
  background: #000;
}

.live-video {
  width: 100%;
  height: 400rpx;
}

.button {
  text-align: center;
  width: 170rpx;
  height: 66rpx;
  line-height: 66rpx;
  margin-left: 10rpx;
  border-radius: 10rpx;
  background-color: #3478F7;
  color: azure;
  font-size: 28rpx;
}
/* .sc{
  position: absolute;
  top: 700rpx;
  bottom: 0rpx;
  opacity: 0.40;
} */

js

const app = getApp();
var socketOpen = false;
var frameBuffer_Data, session, SocketTask;
var url = 'ws://49.???.??.???:9501';//我调用的宝塔的聊天demo
var upload_url ='请填写您的图片上传接口地址';
var inputVal = '';
var msgList = [];
var windowWidth = wx.getSystemInfoSync().windowWidth;
var windowHeight = wx.getSystemInfoSync().windowHeight;
var keyHeight = 0;


/**
 * 初始化数据
 */
function initData(that) {
  inputVal = '';

  msgList = [{
      style: 'bubble you',
      contentType: 'text',
      data: '欢迎来到王者农药,敌军还有30秒到达战场,请做好准备!'
    },
    {
      style: 'bubble me',
      contentType: 'text',
      data: '我怕是走错片场了...'
    }
  ]
  that.setData({
    msgList,//敌军的聊天
    inputVal//我的聊天
  })
}

/**
 * 计算msg总高度
 */
// function calScrollHeight(that, keyHeight) {
//   var query = wx.createSelectorQuery();
//   query.select('.scrollMsg').boundingClientRect(function(rect) {
//   }).exec();
// }

   //生成随机颜色
   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('')
  }

Page({

  /**
   * 页面的初始数据
   */
  data: {
    scrollHeight: '100vh',
    inputBottom: 0
  },

  getDanmu:function(event){
   
    this.setData({
      danmuTxt:event.detail.value,
      
    })
  },
  sendDanmu:function(event){
    let text = this.data.danmuTxt
    this.setData({
      inputVal : ''
    })
    this.videoCtx.sendDanmu({
    text:text,
    
      color:getRandomColor()
    })
  },
  playVideo:function(event){
    this.videoCtx.stop()
    //停止播放之前正在播放的视频
    this.setData({
      src:event.currentTarget.dataset.url
    })
    //更新视频地址
    this.videoCtx.play()
    //播放新的视频
  },
 
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    initData(this);
    this.videoCtx = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (!socketOpen) {
      this.webSocket()
    }
  },

   // 页面加载完成
   onReady: function () {
    var that = this;
    SocketTask.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res)
    })
    SocketTask.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
      this.webSocket()
    })
    SocketTask.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
    })
    SocketTask.onMessage(onMessage => {
      console.log(onMessage)
      this.data.msgList.push(JSON.parse( onMessage.data))
      
      console.log(this.data.msgList)
     this.setData({
       msgList:this.data.msgList
     })
    })
  },

  webSocket: function () {
    // 创建Socket
    SocketTask = wx.connectSocket({
      url: url,
      data: 'data',
      header: {
        'content-type': 'application/json'
      },
      method: 'post',
      success: function (res) {
        console.log('WebSocket连接创建', res)
      },
      fail: function (err) {
        wx.showToast({
          title: '网络异常!',
        })
        console.log(err)
      },
    })
  },

  // 提交文字
  submitTo: function (e) {
    let that = this;
    var data = {
      body: that.data.inputValue,
    }
    if (socketOpen) {
      // 如果打开了socket就发送数据给服务器
      console.log(data)
      sendSocketMessage(data)
    
      this.setData({
        msgList: this.data.msgList,
        inputValue: ''
      })
 
      that.bottom()
    }
  },
  bindKeyInput: function (e) {
    
    this.setData({
      inputValue: e.detail.value
    })
  },
 
  onHide: function () {
    SocketTask.close(function (close) {
      console.log('关闭 WebSocket 连接。', close)
    })
  },
 
  addImg: function () {
    this.setData({
      addImg: !this.data.addImg
    })
 
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 获取聚焦
   */
  focus: function(e) {
    keyHeight = e.detail.height;
    this.setData({
      scrollHeight: (windowHeight - keyHeight) + 'px'
    });
    this.setData({
      toView: 'msg-' + (msgList.length - 1),
      inputBottom: keyHeight + 'px'
    })
    //计算msg高度
    // calScrollHeight(this, keyHeight);

  },

  //失去聚焦(软键盘消失)
  blur: function(e) {
    this.setData({
      scrollHeight: '100vh',
      inputBottom: 0
    })
    this.setData({
      toView: 'msg-' + (msgList.length - 1)
    })

  },

  /**
   * 发送点击监听
   */
  sendClick: function(e) {
    var data = {
      body: e.detail.value,
    }
    if (socketOpen) {
      // 如果打开了socket就发送数据给服务器
      console.log(data)
      sendSocketMessage(data)
    }
   
    inputVal = '';
    this.setData({
      msgList: this.data.msgList,
      inputVal
    })
    // this.setData({
    //   msgList,
    //   inputVal
    // });


  },

  /**
   * 退回上一页
   */
  toBackClick: function() {
    wx.navigateBack({})
  }
  

})

//通过 WebSocket 连接发送数据,需要先 wx.connectSocket,并在 wx.onSocketOpen 回调之后才能发送。
function sendSocketMessage(msg) {
  var that = this;
  console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
  
  var body=JSON.stringify(msg.body)
  console.log(body.replace(/\"/g, ""))
  SocketTask.send({
    data: body.replace(/\"/g, "")
  }, function (res) {
    console.log('已发送', res)
  })
} 

Logo

致力于链接即构和开发者,提供实时互动和元宇宙领域的前沿洞察、技术分享和丰富的开发者活动,共建实时互动世界。

更多推荐