介绍小程序聊天群,发送语音,文字,图片

可以创建群,邀请群成员,群成员列表展示,图片发送,设置群公告,踢人,全体禁言,个人禁言,发送语音信息等功能。

效果图:

实现代码:

wxml

<view class="bo">
  <view class="top_bo">
    <view bindtap="number">群成员({{userNumber}})</view>
    <view bindtap="upLoad" wx:if="{{prohibit=='0'}}">发图片</view>
    <view bindtap="prohibitTis" wx:if="{{prohibit=='1'}}">发图片</view>
    <view bindtap="notice">群公告</view>
    <view bindtap="goHome">去首页</view>
  </view>
  <scroll-view scroll-y="true" scroll-with-animation scroll-top="{{scrollTop}}">
    <block wx:if='{{!list}}'>
      <view class="noList">
        <view class="noMsg">暂无聊天数据</view>
      </view>
    </block>
    <block wx:else>
      <view class="body" wx:for='{{list}}' wx:key='index'>

        <view wx:if='{{item.type==1}}' class="right_body">
          <view class="flexRoe posRit">
            <view class="textBo">
              <view class="dataTime">{{item.sendOutname}} {{item.dataTime}}</view>
              <view wx:if="{{item.text!=''}}" class="ritTxt">{{item.text}}</view>
              <image wx:if="{{item.img!=''}}" mode='widthFix' src="{{item.img}}" class="textImg"></image>
              <view wx:if="{{item.voice}}" class="ritTxt2" bindtap='my_audio_click' src='{{item.voice}}'>
                <image class='my_audio' src='/img/play.png'></image>
              </view>
            </view>
            <image class="head" style=" margin-left:20rpx " src="{{item.sendOutHand}}"></image>
          </view>
        </view>
        <view wx:if='{{item.type==2}}' class="p_r left_body">
          <view class="flexRoe ">
            <image class="head" style=" margin-left:20rpx " src="{{item.sendOutHand}}"></image>
            <view class="lfBo">
              <view class="dataTime">{{item.sendOutname}} {{item.dataTime}}</view>
              <view wx:if="{{item.text!=''}}" class="lftTxt">{{item.text}}</view>
              <image wx:if="{{item.img!=''}}" mode='widthFix' src="{{item.img}}" class="textImg"></image>
              <view wx:if="{{item.voice}}" class="lftTxt2" bindtap='my_audio_click' src='{{item.voice}}'>
                <image class='my_audio' src='/img/play.png'></image>
              </view>
            </view>
          </view>
        </view>
      </view>
    </block>

  </scroll-view>

  <view class="inp">
    <view>
      <view class="p_r" wx:if="{{prohibit=='0'}}">
        <input class="input" placeholder-class='plaCC' confirm-type="send" bindconfirm='sendOut' placeholder='聊天,在这里' value="{{title}}"></input>
        <view class="yuyin" catchtouchstart='voice_ing_start' catchtouchend="voice_ing_end">语音</view>
      </view>
      <view wx:if="{{prohibit=='1'}}" bindtap="prohibitTis" class="prohibit">禁言中</view>
    </view>
  </view>
</view>

wxss

page {
  background: #f2f2f2;
}

.top_bo {
  display: flex;
  background: white;
  flex-direction: row;
}

.top_bo view {
  flex: 1;
  font-size: 28rpx;
  text-align: center;
  border: 1rpx solid #ccc;
  line-height: 80rpx;
}

scroll-view {
  height: 82vh;
  /* padding-bottom: 30rpx; */
}

.noList {
  background: white;
  margin-top: 30rpx;
  /* height: 230rpx; */
  width: 100%;
  padding-top: 25%;
}

.noMsg {
  text-align: center;
  color: #999;
  font-size: 28rpx;
}

.inp {
  position: absolute;
  bottom: 0;
  width: 100%;
  background: white;
  height: 100rpx;
}

.inp input {
  background: #d0d0d0;
  border-radius: 15rpx;
  padding-left: 20rpx;
  height: 84rpx;
  margin-top: 10rpx;
  width: 94%;
  margin-left: 2%;
}

.prohibit {
  background: #d0d0d0;
  border-radius: 15rpx;
  padding-left: 20rpx;
  height: 84rpx;
  margin-top: 10rpx;
  width: 94%;
  margin-left: 2%;
  text-align: center;
  line-height: 84rpx;
  color: rgb(34, 34, 34);
}

.plaCC {
  margin-left: 5rpx;
}

.p_r {
  display: flex;
  flex-direction: row;
}

.flexRoe {
  display: flex;
  flex-direction: row;
}

.body {
  width: 100%;
  position: relative;
  /* border: 1rpx solid #ccc; *//* height: 200rpx */
}

.right_body {
  width: 100%;
  /* border: 1rpx solid red; */
  padding: 20rpx;
  margin-top: 50rpx;
}

.left_body {
  margin-top: 50rpx;
}

.posRit {
  right: 20rpx;
}

.textBo {
  width: 620rpx;
  text-align: right;
}

.lfBo {
  margin-left: 10rpx;
}

.ritTxt {
  background: #44426a;
  padding: 10rpx 20rpx 10rpx 20rpx;
  color: white;
  border-radius: 15rpx 0 15rpx 15rpx;
  margin-top: 20rpx;
  float: right;
  max-width: 500rpx;
  word-wrap: break-word;
  text-align: left;
}

.ritTxt2 {
  background: white;
  color: white;
  border-radius: 15rpx 0 15rpx 15rpx;
  padding: 0rpx 20rpx 10rpx 20rpx;
  margin-top: 20rpx;
  float: right;
  max-width: 500rpx;
  word-wrap: break-word;
  text-align: left;
}

.lftTxt {
  background: #44426a;
  padding: 10rpx 20rpx 10rpx 20rpx;
  color: white;
  border-radius: 0rpx 15rpx 15rpx 15rpx;
  margin-top: 20rpx;
  float: left;
  max-width: 500rpx;
  word-wrap: break-word;
  text-align: left;
}
.lftTxt2 {
  background: #fff;
  padding: 0rpx 20rpx 10rpx 20rpx;
  color: white;
  border-radius: 0rpx 15rpx 15rpx 15rpx;
  margin-top: 20rpx;
  float: left;
  max-width: 500rpx;
  word-wrap: break-word;
  text-align: left;
}
.my_audio {
  height: 60rpx;
  width: 60rpx;
  z-index: 2;
  position: relative;
  top: 10rpx;
  left: 20rpx;
  margin-right: 30rpx;
}


.dataTime {
  font-size: 28rpx;
}

.textImg {
  width: 200rpx;
  margin-top: 5rpx;
}

.head {
  width: 80rpx;
  height: 80rpx;
}

._ {
  height: 130rpx;
  width: 100%;
  background: #ccc;
}

.inpBo {
  display: flex;
  flex-direction: row;
}

.yuyin {
  flex: 1;
  line-height: 104rpx;
  text-align: center;
}

.input {
  flex: 5;
}

js

const DB = wx.cloud.database()
var util = require('../../utils/util.js');
var recorder = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext() //获取播放对象
var qunId, that;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    userNumber: '0',
    userList: [],
    c: "",
    prohibit: '',
  },

  // 点击录音开始播放事件
  my_audio_click: function (e) {
    var src = e.currentTarget.dataset.src;
      console.log('url地址', src);
      innerAudioContext.src = src
      innerAudioContext.seek(0);
      innerAudioContext.play();
  },
  // 首页
  goHome() {
    wx.switchTab({
      url: '../group/group'
    })

  },
  
  // 群成员
  number() {
    let userList = JSON.stringify(this.data.userList)
    wx.navigateTo({
      url: '../member/member?qunId=' + qunId,
    })
  },
  bottom: function() {
    var that = this;
    this.setData({
      scrollTop: 100000
    })
  },
  // 动态监听禁言状态
  prohibit() {
    console.log('8888888888888', qunId)
    const watcher = DB.collection('qunList')
      .where({
        _id: qunId
      })
      .watch({
        onChange: function(res) {

          let arr = res.docs[0]
          console.log('动态监听禁言状态', arr._openId + ':' + wx.getStorageSync('openId'))
          let opid = arr._openId
          if (arr.prohibit == '1') {
            if (arr._openId == wx.getStorageSync('openId')) {
              that.setData({
                prohibit: '0'
              })
            } else {
              that.setData({
                prohibit: '1'
              })
            }
          } else {
            const watcher = DB.collection('qunUserList')
              .where({
                qunId: qunId,
                _openId: wx.getStorageSync('openId')
              })
              .watch({
                onChange: function(res) {

                  let arrr = res.docs[0]
                  console.log('动态监听禁言状态', arrr._openId + ':' + wx.getStorageSync('openId'))
                  if (arrr.prohibit == '1') {
                    if (arrr._openId == opid) {
                      that.setData({
                        prohibit: '0'
                      })
                    } else {
                      that.setData({
                        prohibit: '1'
                      })
                    }
                  } else {
                    that.setData({
                      prohibit: '0'
                    })
                  }


                },
                onError: function(err) {
                  // console.error('----------------error', err)
                }
              })
          }


        },
        onError: function(err) {
          // console.error('----------------error', err)
        }
      })
  },

  // 禁言提示
  prohibitTis() {
    wx.showToast({
      title: '禁言中......',
      icon: 'none'
    })
  },
  // 获取成员消息
  onMsg(qunId) {
    console.log('2222222', qunId)
    const watcher = DB.collection('news')
      // 按 progress 降序
      // .orderBy('progress', 'desc')
      // 取按 orderBy 排序之后的前 10 个
      // .limit(10)
      .where({
        _qunId: qunId
      })
      .watch({
        onChange: function(snapshot) {
          console.log('snapshot', snapshot)
          var listArr = snapshot.docs;
          console.log('---', listArr)
          listArr.forEach((item, idx) => {
            console.log('---', item)
            console.log(wx.getStorageSync('openId') + ':' + item._openId)
            item.type = wx.getStorageSync('openId') == item._openId ? 1 : 2;
            item.sendOutname = wx.getStorageSync('openId') == item._openId ? '我' : '';
          })

          that.setData({
            list: listArr
          })
          setTimeout(() => {
            that.bottom()
          }, 500)
          console.log('-----------------------s', listArr)
        },
        onError: function(err) {
          console.error('----------------error', err)
        }
      })
  },
  // 发送图片
  upLoad() {
    var that = this
    // 让用户选择一张图片
    wx.chooseImage({
      success: chooseResult => {
        // 将图片上传至云存储空间
        wx.cloud.uploadFile({
          // 指定上传到的云路径
          cloudPath: util.imgName() + 'textImg.png',
          // 指定要上传的文件的小程序临时文件路径
          filePath: chooseResult.tempFilePaths[0],
          // 成功回调
          success: res => {
            console.log('上传成功', res)
            let imgUrl = res.fileID
            wx.cloud.callFunction({
              name: "news",
              // data: {
              //   imgUrl: imgUrl
              // },
              data: {
                _qunId: qunId,
                _openId: wx.getStorageSync('openId'),
                // 消息
                text: '',
                // 消息
                img: imgUrl,
                // 时间
                dataTime: util.nowTime(),
                // 头像
                sendOutHand: wx.getStorageSync('userInfo').avatarUrl,
                // 昵称
                sendOutname: wx.getStorageSync('userInfo').nickName
              },
              success(res) {
                console.log('图片发送成功', res)
              },
              fail(res) {
                console.log('返回失败', res)
              }
            })
          },
        })
      },
    })
  },
  onLoad: function(options) {
    console.log(options)
    that = this
    qunId = options.qunId
    this.onMsg(options.qunId);
    that.userFun()
    that.prohibit()

  },
  // 获取群成员
  userFun() {
    DB.collection('qunUserList').where({
        qunId: qunId
      })
      .get({
        success: function(res) {
          console.log(666666666, res)
          that.setData({
            userNumber: res.data.length,
            userList: res.data
          })

        }
      })
  },

  // 群公告
  notice() {
    wx.showModal({
      title: '群公告',
      content: this.data.userList[0].qunTitle,
      showCancel: false,
      success(res) {
        if (res.confirm) {
          // console.log('用户点击确定')
        }
      }
    })
  },
  // 发送消息
  sendOut(e) {
    console.log(1111, e)
    let title = e.detail.value
    if (title == '') {
      wx.showToast({
        title: '请输入聊天内容',
        icon: 'none',
      })
    } else {
      var data = {
        _qunId: qunId,
        _openId: wx.getStorageSync('openId'),
        // 消息
        text: title,
        // 消息
        img: '',
        // 时间
        dataTime: util.nowTime(),
        // 头像
        sendOutHand: wx.getStorageSync('userInfo').avatarUrl,
        // 昵称
        sendOutname: wx.getStorageSync('userInfo').nickName
      }
      console.log(data)
      wx.cloud.callFunction({
        name: "news",
        data: data,
        success(res) {
          console.log('消息发送', res)
          that.setData({
            title: ''
          })

        },
        fail(res) {
          console.log('登录失败', res)
        }
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },

  // 手指点击录音
  voice_ing_start: function () {
    console.log('手指点击录音')
    wx.showToast({
      title: '按住录音,松开发送',
      icon: 'none'
    })
    this.setData({
      voice_ing_start_date: new Date().getTime(), //记录开始点击的时间
    })
    const options = {
      duration: 10000, //指定录音的时长,单位 ms
      sampleRate: 8000, //采样率
      numberOfChannels: 1, //录音通道数
      encodeBitRate: 24000, //编码码率
      format: 'mp3', //音频格式,有效值 aac/mp3
      audioSource: 'auto',
      frameSize: 12, //指定帧大小,单位 KB
    }
    recorder.start(options) //开始录音

    this.animation = wx.createAnimation({
      duration: 1200,
    }) //播放按钮动画
    that.animation.scale(0.8, 0.8); //还原
    that.setData({

      spreakingAnimation: that.animation.export()
    })
  },
  onReady: function () {
    this.on_recorder();
  },

  // 录音监听事件
  on_recorder: function () {
    console.log('录音监听事件');
    recorder.onStart((res) => {
      console.log('开始录音');
    })
    recorder.onStop((res) => {
      let {
        tempFilePath
      } = res;
      console.log('停止录音,临时路径', tempFilePath);
      var x = new Date().getTime() - this.data.voice_ing_start_date
      if (x > 1000) {
        let timestamp = new Date().getTime();
        wx.cloud.uploadFile({
          cloudPath: "sounds/" + timestamp + '.mp3',
          filePath: tempFilePath,
          success: res => {
            console.log('上传成功', res)
            that.setData({
              soundUrl: res.fileID,
            })

            var data = {
              _qunId: 'fb16f7905e4bfa24009098dc34b910c8',
              _openId: wx.getStorageSync('openId'),
              // 消息
              text: '',
              voice: res.fileID,
              img: '',
              // 时间
              dataTime: util.nowTime(),
              // 头像
              sendOutHand: wx.getStorageSync('userInfo').avatarUrl,
              // 昵称
              sendOutname: wx.getStorageSync('userInfo').nickName
            }
            console.log(data)
            wx.cloud.callFunction({
              name: "news",
              data: data,
              success(res) {
                console.log('发送语音发送', res)
              },
              fail(res) {
                console.log('发送语音失败', res)
              }
            })
          },
        })
      }
    })
    recorder.onFrameRecorded((res) => {
      return
      console.log('onFrameRecorded  res.frameBuffer', res.frameBuffer);
      string_base64 = wx.arrayBufferToBase64(res.frameBuffer)

      console.log('string_base64--', string_base64)
    })
  },
  // 手指松开录音
  voice_ing_end: function () {
    console.log('手指松开录音')

    that.setData({
      voice_icon_click: false,
      animationData: {}
    })
    this.animation = "";
    var x = new Date().getTime() - this.data.voice_ing_start_date
    if (x < 1000) {
      console.log('录音停止,说话小于1秒!')
      wx.showModal({
        title: '提示',
        content: '说话要大于1秒!',
      })
      recorder.stop();
    } else {
      // 录音停止,开始上传
      recorder.stop();
    }
  },
  // 点击语音图片
  voice_icon_click: function () {
    this.setData({
      voice_icon_click: !this.data.voice_icon_click
    })
  },
})

相关免费学习推荐:微信小程序开发教程

以上就是介绍小程序聊天群,发送语音,文字,图片的详细内容,更多请关注编程之家其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


概述 消息能力是小程序能力中的重要组成,我们为开发者提供了订阅消息能力,以便实现服务的闭环和更优的体验。 订阅消息推送位置:服务通知 订阅消息下发条件:用户自主订阅 订阅消息卡片跳转能力:点击查看详情可提爱转至该小程序的页面 消息类型 一次性订阅消息 一次性订阅消息用于解决用户使用小程序后,后续服务
判断H5页面环境在微信中还是小程序中 用小程序提供的wx.miniProgram.getEnv可以获取环境参数 &lt;script type=&quot;text/javascript&quot; src=&quot;https://res.wx.qq.com/open/js/jweixin-1.
wx.reLaunch和wx.navigateTo,wx.navigateTo的区别 2019-03-23 11:18:05 wx.navigateTo 用于保留当前页面、跳转到应用内的某个页面,使用 wx.navigateBack可以返回到原页面。对于页面不是特别多的小程序,通常推荐使用 wx.n
微信小程序如何从数组里取值_微信小程序 传值取值的几种方法总结 小程序里常见的取值有以下几种,一个完整的项目写下来,用到的概率几乎是100%。 列表index下标取值 页面传值 form表单取值 1. 列表index下标取值 实现方式是:data-index=&quot;{{index}}&quot
H5项目接入微信授权登录,通过 UA 区分微信还是普通浏览器: let&#160;ua&#160;=&#160;navigator.userAgent.toLowerCase(); let&#160;isWeixin&#160;=&#160;ua.indexOf(&#39;micromessenge
微信小程序获取data-xx=&quot;&quot;属性的值,自定义属性设置和获取(data-) 微信小程序&lt;view class=&quot;details-btn&quot; data-taskId=&quot;111&quot; bindtap=&#39;taskdetails&#39
小程序报错:TypeError: Cannot read property ‘addEventListener‘ of undefined 解决办法 将调试基础库由2.16.0(或者当前的) -&gt; 2.14.1 解决问题
H5跳转微信小程序-成功案例(VUE)(踩坑无数) TuoMei 已于 2022-07-29 09:52:22 修改 准备工作 根据官方提供的资料需准备以下几点: 1、已认证的服务号 2、绑定JS接口安全域名 (在微信公众平台设置) 3、IP白名单 (在微信公众平台设置) 4、将小程序和H5公众号进
微信小程序 页面跳转和数据传递实例详解 这篇文章主要介绍了微信小程序 页面跳转和数据传递实例详解的相关资料,这里附有实例代码帮助到家学习理解,需要的朋友可以参考下 微信小程序 页面跳转和数据传递 1.先导 在Android中,我们Activity和Fragment都有栈的概念在里面,微信小程序页面也
情景1.拉取公司代码演示: 因为github有墙,这里我们以gitee(码云)为例作为演示 (其实就是国产github,也非常好用~) 步骤一:打开Git界面 先在一个空文件夹右击Git Bash Here,打开git界面 步骤二:输入克隆远程仓库指令 别人复制的链接在这里获取 拿到别人赋值的链接自
如何开发微信小程序? 作为一名10多年一直从事互联网平台开发的从业者,我来回答下这个问题吧。 微信小程序开发流程总体可以归纳为4个步骤, 老张带您捋一捋整个环节,小白用户可以收藏了。 好了废话不多说,开始! 一、开发前小程序需要准备的资料 我们在开发微信小程序前,需要准备下相关资料。这个资料主要是后
原生小程序开发优化方案 为了更好的制定优化方案,我们 有必要先了解下小程序的底层架构、以及与普通网页开发的差异 小程序最终渲染载体与当下一些热门的技术 Flutter、React Native等不同,依然是浏览器内核,而不是原生客户端。 而对于传统的网页来说,UI 渲染和 JS 脚本是在同一个线程中
1,不要下两倍尺寸的图片, 小程序本身自己就会对元素缩小两倍,设计图片的一杯就已经很清晰了。 2,图片压缩,(主要是压缩静态资源,ps 可以压缩,然后有一些在线压缩工具,保持600-800kb 的静态) 3,通用的代码组件化 4,是在工程量太大可以分包,分包现在最大支持20m(一般都不会去分包的)
文章浏览阅读189次。人工智能研究实验室OpenAI在2022年11月30日发布了自然语言生成模型ChatGPT,上线两个月就已经超过一亿用户,成为了人工智能界当之无愧的超级大网红。ChatGPT凭借着自身强大的拟人化及时应答能力迅速破圈,引起了各行各业的热烈讨论。简单来说ChatGPT就是可以基于用户文本输入自动生成回答的人工智能聊天机器人。那肯定会有人说这不就是Siri嘛,虽然都是交互机器人但是两者的差别可老大了。那么ChatGPT在人机交互时为什么会有这么出色的表现?它到底会不会取代搜索引擎?90%的人真的会因为ChatG
文章浏览阅读193次。8. 导航和路由管理:掌握小程序的导航方式,如使用wx.navigateTo跳转页面、使用wx.redirect重定向页面等,学会实现页面之间的跳转和传参。1. 小程序的基本概念和架构:了解小程序的定义、特点以及与传统APP的区别,掌握小程序的运行环境、组件和API等基本概念。10. 支付功能:学习小程序的支付方式,如微信支付、支付宝支付等,了解支付流程和注意事项,学会实现小程序的支付功能。9. 用户授权和登录:了解小程序的用户授权机制,如获取用户信息、调用微信API等,学会实现用户的登录和注册功能。_微信小程序开发知识点总结
文章浏览阅读4.8k次,点赞7次,收藏18次。一、准备工作1. 安装微信开发者工具,并登录微信小程序账号;2. 准备斗地主游戏的图片资源;3. 准备斗地主游戏的音效资源;二、创建小程序1. 打开微信开发者工具,点击“新建小程序”,输入小程序名称,选择小程序的项目目录,点击“创建”;2. 在小程序的项目目录中,新建文件夹“images”,将准备好的斗地主游戏的图片资源放入“images”文件夹中;3. 在小程序的项目目录中,新建文件夹“sounds”,将准备好的斗地主游戏的音效资源放入“sounds”文件夹中;三、编写代码1. 在小程_扑克牌微信小程序代码
文章浏览阅读3.9k次,点赞3次,收藏7次。一、准备工作:1. 安装微信开发者工具,创建小程序项目;2. 准备游戏角色图片;3. 准备游戏背景音乐;二、实现步骤:1. 创建游戏页面,添加游戏角色图片,添加游戏背景音乐;2. 创建游戏角色类,定义游戏角色属性,如角色名称、角色图片、角色能力等;3. 创建游戏类,定义游戏属性,如游戏人数、游戏角色、游戏规则等;4. 创建游戏控制类,定义游戏流程,如游戏开始、游戏结束、游戏角色分配等;5. 创建游戏界面,实现游戏流程,如游戏开始、游戏结束、游戏角色分配等;6. 创建游戏结果页面,显示游戏_微信小程序游戏代码
文章浏览阅读1.7k次。1. 创建小程序项目:使用微信开发者工具创建一个小程序项目,并在项目中添加一个页面,用于模拟聊天。 2. 定义数据结构:定义一个数据结构,用于存储聊天记录,包括发送者、接收者、消息内容等信息。 3. 实现聊天功能:实现聊天功能,包括发送消息、接收消息、显示消息等功能。 4. 实现界面:使用微信小程序的界面框架,实现聊天界面,包括聊天记录列表、输入框等。代码示例:// 定义数据结构var chatData = { sender: '', receiver: '', message: '' };_制作聊天对话小程序代码
文章浏览阅读2.1k次。1、创建小程序项目:使用微信开发者工具,新建一个小程序项目,输入项目名称,选择项目目录,点击“创建”按钮,即可创建小程序项目。2、添加页面:在小程序项目中,可以添加多个页面,每个页面都有自己的页面文件,比如首页、分类页、购物车页、我的页面等。3、添加组件:在小程序项目中,可以添加多个组件,比如商品列表组件、购物车组件、订单组件等,用于在页面中显示商品信息、购物车信息、订单信息等。4、添加接口:在小程序项目中,可以添加多个接口,用于获取商品信息、购物车信息、订单信息等,以便在页面中显示。5、_微信开发者工具做一个我的商城