chat-sdk-ws
v1.0.3
Published
- npm 方式:
Downloads
5
Readme
使用方法
引入方式
- npm 方式:
安装:
npm i chat-sdk-ws
调用:
import ChatSDK from 'chat-sdk-ws'
let chat = new ChatSDK()
API
WebSocket 初始化: initWS(url, msgCallback, openCallback, errCallback, closeCallback)
demo:
// 参数说明: url: WebSocket url msgCallback: WebSocket监听消息的回调, openCallback: 连接成功的回调, errCallback: 断开连接的回调, closeCallback: 关闭连接的回调)
chat.initWS(
'wss://xxxxxxxxxx',
(res) => {
console.log(res) // res为WebSocket里onMessage接收到的消息
},
() => {
console.log('连接成功')
},
() => {
console.log('断开连接')
},
() => {
console.log('连接已关闭')
}
)
res 参数说明:
{
current_group_data, // 当前所处群组的成员数据
data, // 所有数据,包括群组列表以及群组内成员数据
dev_group, // 当前所处群组
dev_id, // 当前群组的调度平台
msg_type, // 消息类型
}
获取麦克风权限: tryGetPermission()
demo:
// 调用initWS()方法默认调用tryGetPermission()方法
chat.tryGetPermission()
检查是否有权限: checkPermission()
demo:
chat.checkPermission()
- 返回值: Boolean 类型
新的语音消息到来时的回调: setAudioMsgRecvCallback(callback)
demo:
chat.setAudioMsgRecvCallback((e) => {
console.log(e) // e为语音消息数据
})
获取所有设备当前状态: getAllDevStatus()
demo:
chat.getAllDevStatus().then((res) => {
console.log(res) // res为请求成功的返回值
})
- 返回一个 Promise,需要调.then 方法
创建群组,邀请设备成员并进入群组: addGroupAndEnter(car_plates)
demo:
// car_plates: 传入数据类型为数组,数组元素为设备的car_plate字段元素 返回一个Promise,需要调.then方法
// 成员邀请要求: 每个成员需要满足: 1.在线(is_online = true) 2.当前设备没有被其他人占用(is_busy = false)
// 调用本方法前,先调用getAllDevStatus()获取所有设备当前状态,传入合要求的car_plate数组
chat.addGroupAndEnter(['豫AXXX', '豫AXXY']).then((res) => {
console.log(res) // res为传入参数之后的返回值
})
开始录音: startRecord(callback)
demo:
// 参数说明:
// callback: 开始录音后的回调
chat.startRecord(() => {
console.log('开始录音')
})
结束录音并发送语音消息: endRecord(callback)
demo:
// 参数说明:
// callback: 结束录音后的回调
chat.endRecord((res) => {
console.log(res) // res为结束录音后接收到的数据
})
res 参数说明:
{
msg_type: 'new_audio_data', // 消息格式,当为new_audio_data则说明该数据是一条语音
from_dev: 'WS',
from_dev_name: '我',
arrayBuffer, // 语音buffer格式
time // 语音时长
}
播放录音: playAudioMsg(audioMsg, callback)
demo:
// 参数说明:
// audioMsg: 播放的语音数据(类型: 可传两种类型: ArrayBuffer/base64字符串)
// callback: 播放结束的回调
chat.playAudioMsg(audioMsg, () => {
console.log('播放结束')
})
// 一般通过平台录的音返回的是ArrayBuffer类型, 接收消息返回的是base64字符串,
// 所以播放录音传参数时可以这样写:
chat.playAudioMsg(item.arrayBuffer || item.b64_data, () => {
console.log('播放结束')
})
销毁连接 并退出群组: destroyConnect()
demo:
chat.destroyConnect()
ArrayBuffer 转 base64 方法: arrayBufferToBase64()
demo:
chat.arrayBufferToBase64(buffer)
- 返回一个 base64 字符串
base64 转 ArrayBuffer 方法: base64ToArrayBuffer()
demo:
chat.base64ToArrayBuffer(base64)
- 返回一个 ArrayBuffer