集成网易云信SDK,进行即时通信-Web(语音通信)

本文档介绍了如何集成网易云信SDK进行即时通信,特别是Web端的语音通信功能。首先,需要在网易云信控制台创建uikit获取appKey,并了解可用服务。接着,查阅开发文档和选择合适的SDK集成方式,推荐使用npm集成。在集成过程中,初始化SDK,处理语音消息的发送,包括请求浏览器语音授权。最后,通过封装组件实现语音消息的收发及历史消息获取。若需更多功能,可参考官方API文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、进行网易云信账号登录注册

登录网易云信控制台
1.登录后可在控制台创建uikit,获取自己appKey
2.查看自己所开通的服务
在这里插入图片描述
在这里插入图片描述
这边是没有语音通信权限的,可以申请免费试用

二、进行文档查看

开发文档
可以看到一些demo,各个平台和环境下API
在这里插入图片描述
选择自己开发的环境,选择下面的不含UI集成(根据自己需求选择适合自己的)
在这里插入图片描述

三、进行SDK集成

方式1: npm 集成(推荐)

npm install @yxim/nim-web-sdk@latest

方式2:script 集成

1.前往云信 SDK 下载中心下载最新版 SDK
2.解压 SDK。SDK 解压后可得到以下三个文件(配图仅以 v9.8.0 为例)
在这里插入图片描述
3. 三个文件说明

├── NIM_Web_Chatroom.js       提供聊天室功能,浏览器适配版(UMD 格式)
├── NIM_Web_NIM.js       提供 IM 功能,包括单聊、会话和群聊等,但不包含聊天室。浏览器适配版(UMD 格式)
├── NIM_Web_SDK.js       提供 IM 功能和聊天室功能的集成包,浏览器适配版(UMD 格式)

4.将所需的 SDK 文件,传入script标签的src中即可。在下文中使用 window 对象属性即可获取对 SDK 的引用。

<!-- 例如 -->
<script src="NIM_Web_SDK_vx.x.x.js">
<script>
  var nim = SDK.NIM.getInstance({
   
    // ...
  })
</script>

更详细的可去往网易云信官方文档

这边自己是通过方式一进行添加,然后封装在工具中的ts文件中
utils文件夹中的Nim.ts中

/*
 * @Description: 即使通信
 * @Author: 黑猫
 * @Date: 2023-06-30 10:53:33
 * @LastEditTime: 2023-07-15 10:26:36
 * @FilePath: \pc-exam-invigilate\src\utils\Nim.ts
 */
import {
    NIM } from '@yxim/nim-web-sdk'
// import { NimSdk, NimScene } from '@/constants'
import type {
   
  NIMSendTextOptions,
  NIMGetInstanceOptions,
  NIMSession,
  INimInstance
} from '@/types/NimTypes'

type CallbackOptions =
  | 'onconnect'
  | 'ondisconnect'
  | 'onerror'
  | 'onmsg'
  | 'onwillreconnect'
  | 'onsessions'
  | 'onupdatesessions'
  | 'onofflinemsgs'
type Options = {
   
  account: string
  token: string
  debug?: boolean
} & Pick<NIMGetInstanceOptions, CallbackOptions>

class Nim {
   
  nim
  constructor(options: Options) {
   
    this.nim = this.initNim(options)
  }
  private initNim({
    account, token, debug = true, ...args }: Options): INimInstance {
   
    console.log(import.meta.env.VITE_APP_KEY)
    return NIM.getInstance({
   
      debug,
      appKey: import.meta.env.VITE_APP_KEY,
      account,
      token,
      privateConf: {
   
        isDataReportEnable: true,
        isMixStoreEnable: true
      }, // 私有化部署方案所需的配置
      ...args
    })
  }
  // 发送文本消息
  sendText(options: NIMSendTextOptions) {
   
    this.nim.sendText({
   
      cc: true,
      ...options
    })
  }
  // 重置会话未读数
  resetSessionUnread(
    sessionId: string,
    done: (err: Error | null, failedSessionId: string) => void
  ) {
   
    this.nim.resetSessionUnread(sessionId, done)
  }
  // 获取历史记录
  getHistoryMsgs(options: any) {
   
    this.nim.getHistoryMsgs(options)
  }
  sendCustomMsg(options: any) {
   
    this.nim.sendCustomMsg(options)
  }
  getTeam(options: any) {
   
    this.nim.getTeam(options)
  }
  getTeams(options: any) {
   
    this.nim.getTeams(options)
  }
  sendFile(options: any) {
   
    this.nim.sendFile(options)
  }
  // 合并会话列表
  mergeSessions(olds: any[], news: any[]) {
   
    if (!olds) {
   
      olds = []
    }
    if (!news) {
   
      return olds
    }
    if (!NIM.util.isArray(news)) {
   
      news = [news]
    }
    if (!news.length) {
   
      return olds
    }
    const options = {
   
      sortPath: 'time',
      desc: true
    }
    return NIM.util.mergeObjArray([], olds, news, options)
  }
  destory(done?: any) {
   
    this.nim.destroy(done)
  }
  disconnect(done?: any) {
   
    this.nim.disconnect(done)
  }
}

export default Nim

types中的NimTypes.ts

/*
 * @Description: 功能
 * @Author: 黑猫
 * @Date: 2023-06-30 11:01:57
 * @LastEditTime: 2023-06-30 14:18:22
 * @FilePath: \pc-exam-invigilate\src\types\NimTypes.ts
 */
import {
    NIM } from '@yxim/nim-web-sdk'
import type {
    NIMCommonError, NIMStrAnyObj } from '@yxim/nim-web-sdk/dist/types/types'
export type {
   
  NIMSendTextOptions,
  NIMMessage
} from '@yxim/nim-web-sdk/dist/types/nim/MessageInterface'
export type {
   
  NIMTeam,
  NIMTeamMember,
  TeamInterface
} from '@yxim/nim-web-sdk/dist/types/nim/TeamInterface'
export type {
    NIMGetInstanceOptions } from '@yxim/nim-web-sdk/dist/types/nim/types'
export type {
    NIMSession } from '@yxim/nim-web-sdk/dist/types/nim/SessionInterface'
export type NIMError = NIMCommonError | Error | NIMStrAnyObj | null
export type INimInstance = InstanceType<typeof NIM>

1.现在进行初始化

// 获取历史消息
const getHistoryMessages = (teamId: string) => {
   
  const today = new Date()
  const threeDaysAgo = new Date(today.getTime() - 2 * 24 * 60 * 60 * 1000) // 两天前的日期
  today.setHours(0, 0, 0, 0)
  threeDaysAgo.setHours(0, 0, 0, 0)
  const beginTime = threeDaysAgo.getTime()
  const endTime = Date.now()
  try {
   
    inspectorNimRef.value?.getHistoryMsgs({
   
      scene: NimScene.GroupChat,
      to: teamId,
      beginTime: beginTime,
      endTime: endTime,
      reverse: true, // 是否按照逆序获取历史消息
      done: getHistoryMsgsDone
    })
  } catch (error) {
   
    console.log('获取历史消息错误', error)
  }
}

// 处理历史消息数据
const getHistoryMsgsDone = (error, obj: any) => {
   
  if (!error) {
   
    if (obj.msgs.length > 0) {
   
      obj.msgs.forEach((item) => {
   
        if (item?.file) {
   
          audioMessageList.value.push({
   
            duration: Math.ceil(item?.file?.size / (6600 * 2)),
            stream: item?.file?.url,
            wink: false,
            username: item.fromNick,
            flow: item.flow,
            time: formatDateTime(item.time)
          })
        }
      })
    }
  }
}
// 接收消息
const receiveMessage = (message: NIMMessage) => {
   
  if (message && message.type === 'audio' && message?.to) {
   
    // 处理接收到的语音消息
    const duration = Math.ceil(message.file.size / (6600 * 2))
    if (duration <= 1) {
   
      return
    }
    const dataTime = formatDateTime(message.time)
    audioMessageList.value.push({
   
      duration,
      stream: message.file.url,
      wink: false,
      username: message.fromNick,
      flow: message.flow,
      time: dataTime
    })
    openChatting(true, checkedObj.value)
    // 在此处触发弹窗或其他操作来展示语音消息
  }
}

import {
    refreshImToken } from '@/api/modules/examRoom'
import type {
    NIMMessage } from '@/types/NimTypes'
import {
    NimScene } from '@/constants'
import {
    ref, onMounted, computed } from 'vue'
import Nim from '@/utils/Nim
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值