更新记录
1.0.1(2026-09-04)
【新增】安卓支持 【新增】iOS支持 【新增】对讲降噪效果,企业级降噪。
平台兼容性
uni-app x(4.71)
| Chrome | Safari | Android | iOS | 鸿蒙 | 微信小程序 |
|---|---|---|---|---|---|
| √ | √ | √ | √ | × | × |
前言
uniapp插件采用官方的uts开发:
https://doc.dcloud.net.cn/uni-app-x/plugin/uts-plugin.html
https://doc.dcloud.net.cn/uni-app-x/plugin/uts-plugin-hybrid.html
https://doc.dcloud.net.cn/uni-app-x/plugin/uts-component-compatible.html
https://doc.dcloud.net.cn/uni-app-x/plugin/uts-ios-cocoapods.html
1、安装Uniapp插件
-
创建
uni_modules目录将yn-livekit拖入uni_modules目录中。 -
运行打包自定义基座。
Hbuilderx中点击发行 - App-Android/ios云打包。iOS 开发需准备 Mac 电脑,Iphone 手机,申请 iOS开发者证书才能打包。 -
打包完成后
运行到 APP - 运行到手机或模拟器 - 选择自定义基座
2、SDK API
1. 初始化 initRoom()
说明:该方法需在所有方法之前调用,用于实例化 SDK;调用仅初始化实例不会进入房间。
用法:
import {initRoom} from '@/uni_modules/yn-livekit';
const res = await initRoom();
响应值:
// 成功
{
success: true,
errCode: 0,
errMsg: '初始化完成'
}
// 失败
{
success: false
errCode: 9010001,
errMsg: 'Room 创建失败'
}
2. 进入房间 connectToRoom(url,token)
说明: 根据 /rooms/{name}/join获取的url,token 进入房间。两参数都不能为空。
如要进入房间获取当前房间的人员调用 getRoomParticipants()即可,详见demo。
用法:
import {connectToRoom} from '@/uni_modules/yn-livekit';
const res = await connectToRoom("ws://xxxxx","eyJhbGciOiJIxxxxxx");
3. 断开房间 disconnectFromRoom()
说明:断开当前房间连接;可安全重复调用(若已断开则返回成功)。
用法:
import { disconnectFromRoom } from '@/uni_modules/yn-livekit';
const res = await disconnectFromRoom();
响应值:
// 成功
{
success: true,
errCode: 0,
errMsg: '断开成功',
data: {
state: 'disconnected',
}
}
// 失败(例如 Room 未创建 / 原生异常)
{
success: false,
errCode: 'DISCONNECT_FAILED',
errMsg: '断开失败: xxx'
}
5. 原生事件回调注册 onEvents(callback)
说明:注册原生实时事件回调,推荐在 initRoom() 之后、connectToRoom() 之前调用以避免丢事件。提供的回调将持续接收房间事件(无轮询)。
用法:
import { onEvents } from '@/uni_modules/yn-livekit';
const handleRoomEvent = (ev) => {
// 标准结构:{ eventType: string, payload: UTSJSONObject }
console.log('[RoomEvent]', ev.eventType, ev.payload);
};
const ok = onEvents(handleRoomEvent);
返回值:boolean(true 表示注册成功)。
常见事件类型:
roomConnected:房间连接成功(含roomName、本地参与者信息、当前远端列表)。roomReconnecting/roomReconnected:重连过程与成功。roomDisconnected:房间断开。participantConnected/participantDisconnected:参与者加入/离开。trackPublished/trackUnpublished:轨道发布/取消发布。trackSubscribed/trackUnsubscribed:轨道订阅/取消订阅。trackMuted/trackUnmuted:轨道静音/取消静音。localTrackSubscribed:本地轨道被首次订阅(本地预览就绪的信号)。activeSpeakersChanged:活跃说话者变化。roomMetadataChanged/participantMetadataChanged:房间/参与者元数据变更。connectionQualityChanged:连接质量变化。dataReceived:收到数据通道消息(含payloadBase64)。trackSubscriptionFailed:订阅失败(含错误信息)。
事件回调 payload 字段说明:
roomConnectedroomName:房间名。localParticipantSid:本地参与者 SID。localIdentity:本地参与者 identity。initialParticipants:当前远端参与者标识数组(优先identity,缺失时回退为sid)。
roomReconnecting/roomReconnectedroomName:房间名。
roomDisconnectedroomName:房间名。reason:断开原因枚举名。error:错误描述(可能为空)。
participantConnected/participantDisconnectedparticipantSid:参与者 SID。participantIdentity:参与者 identity。participantName:参与者可读名称(可能为空)。
activeSpeakersChangedroomName:房间名。speakers:活跃说话者 identity 数组。
trackPublished/trackUnpublished/trackSubscribed/trackUnsubscribed/trackMuted/trackUnmuted/localTrackSubscribedparticipantSid:参与者 SID。participantIdentity:参与者 identity。participantName:参与者名称(可能为空)。publicationSid:轨道发布 SID。trackName:轨道名称(如camera)。trackKind:轨道类型(VIDEO/AUDIO)。 注:trackUnsubscribed与以上轨道事件保持相同结构。
roomMetadataChangedroomName:房间名。newMetadata:最新房间元数据字符串(可能为空)。prevMetadata:上一次房间元数据字符串(可能为空)。
participantMetadataChangedparticipantSid:参与者 SID。participantIdentity:参与者 identity。participantName:参与者名称(可能为空)。prevMetadata:上一次参与者元数据(可能为空)。
dataReceivedroomName:房间名。fromSid:发送者参与者 SID。fromIdentity:发送者参与者 identity。topic:消息主题(可能为空)。payloadBase64:消息内容的 Base64 字符串。
trackSubscriptionFailedparticipantSid:参与者 SID。participantIdentity:参与者 identity。trackSid:失败的轨道 SID。error:错误描述。
说明:当前 Android 端未序列化 connectionQualityChanged 事件;如后续加入,通常会包含连接质量等级(如 quality)及参与者身份字段。
6. 释放资源 release()
说明:释放原生 Room 及事件采集资源,并重置插件实例。适用于页面销毁、会话结束、不再复用的场景。该方法会内部执行事件回调清理与断开连接、停止事件采集。
用法:
import { release } from '@/uni_modules/yn-livekit';
// 页面卸载或会话结束时调用
release();
行为说明:
- 清理事件回调(等同
offEvents())。 - 若仍有房间连接,执行断开并停止事件采集。
- 释放 Room 原生对象并置空内部单例,避免旧状态残留。
推荐使用:在页面的 onUnmounted 或组件销毁时仅调用 release() 即可,无需再额外调用 offEvents() 或 disconnectFromRoom()。
7. 取消原生事件回调 offEvents()
说明:取消已注册的原生事件回调;不会影响房间连接状态。
用法:
import { offEvents } from '@/uni_modules/yn-livekit';
offEvents();
返回值:void。
8. 获取房间参与者与轨道快照 getRoomParticipants()
说明:获取当前房间的本地参与者与远端参与者的精简快照,用于前端渲染与状态判定。
用法:
import { getRoomParticipants } from '@/uni_modules/yn-livekit';
const res = await getRoomParticipants();
响应值(成功时 data 示例):
{
success: true,
errCode: 0,
errMsg: 'OK',
data: {
roomName: 'room-abc',
remoteParticipants: [
{
participantSid: 'PS_xxx',
participantIdentity: 'userA',
participantName: '用户A',
tracks: [
{
publicationSid: 'TR_xxx',
name: 'camera',
kind: 'VIDEO',
muted: false,
subscribed: true,
source: 'CAMERA',
width: 1280,
height: 720
}
],
primaryVideoPublicationSid: 'TR_xxx'
}
],
localParticipant: {
participantSid: 'PS_me',
participantIdentity: 'me',
participantName: '我',
tracks: [ /* 同上结构 */ ],
primaryVideoPublicationSid: 'TR_me_video'
}
}
}
失败:success: false,包含 errCode 与 errMsg(如 Room 未创建或未连接)。
9. 获取本地视频轨道信息 getLocalVideoTrackInfo()
说明:快速获取本地视频轨发布信息(用于本地预览渲染与状态校准)。
用法:
import { getLocalVideoTrackInfo } from '@/uni_modules/yn-livekit';
const res = await getLocalVideoTrackInfo();
响应值(成功时 data 示例):
{
success: true,
errCode: 0,
errMsg: 'OK',
data: {
participantSid: 'PS_me',
participantIdentity: 'me',
publicationSid: 'TR_me_video',
trackName: 'camera',
muted: false,
subscribed: true,
source: 'CAMERA',
width: 1280,
height: 720
}
}
失败:success: false(如本地参与者或视频轨不存在)。
10. 开关摄像头 setCameraEnabled(enabled)
说明:开启/关闭本地摄像头。需确保已授权摄像头权限。
用法:
import { setCameraEnabled } from '@/uni_modules/yn-livekit';
// 开启摄像头
await setCameraEnabled(true);
// 关闭摄像头
await setCameraEnabled(false);
响应值:
// 成功
{ success: true, errCode: 0, errMsg: '已开启/已关闭', data: { enabled: true/false } }
// 失败(原生异常等)
{ success: false, errCode: 'UNKNOWN_ERROR', errMsg: 'xxx' }
11. 开关麦克风 setMicrophoneEnabled(enabled)
说明:开启/关闭本地麦克风。需确保已授权麦克风权限。
用法:
import { setMicrophoneEnabled } from '@/uni_modules/yn-livekit';
// 开启麦克风
await setMicrophoneEnabled(true);
// 关闭麦克风
await setMicrophoneEnabled(false);
响应值:
// 成功
{ success: true, errCode: 0, errMsg: '已开启/已关闭', data: { enabled: true/false } }
// 失败(原生异常等)
{ success: false, errCode: 'UNKNOWN_ERROR', errMsg: 'xxx' }
12. 翻转摄像头 switchCamera()
说明:在前置/后置摄像头之间切换。
用法:
import { switchCamera } from '@/uni_modules/yn-livekit';
const res = await switchCamera();
响应值:
// 成功
{ success: true, errCode: 0, errMsg: '已翻转', data: {} }
// 失败
{ success: false, errCode: 'UNKNOWN_ERROR', errMsg: 'xxx' }
RTC播放器
根据Uniapp官方文档 自定义组件 只能在 nvue/uvue 模式下使用,该模式使用weex渲染,达到原生性能。
使用方式
<livekit-video-view ref="localView" style="width: 300px; height: 200px" :localIdentity="localIdentity" />
<livekit-video-view ref="localView" style="width: 300px; height: 200px" :remoteIdentity="remoteIdentity" />
组件说明
- 属性(props):
localIdentity: string本地参与者的 identity,用于渲染本地预览;非空时自动挂载本地视频渲染器。remoteIdentity: string远端参与者的 identity(缺失时可传participantSid作为回退),用于渲染该远端的主视频;非空时自动尝试挂载远端视频渲染器。
推荐的渲染控制
- 使用
v-if控制组件的创建/销毁:当视频不可渲染(未订阅/静音/离开)时移除组件,触发原生NVBeforeUnload/unmounted,更彻底释放资源。
如何获取并传递 localIdentity
获取途径(三选一,推荐优先级 1 > 2 > 3):
1) 连接返回值
const result = await connectToRoom(url, token)
// 成功后可直接读取:
const localIdentity = result?.data?.localIdentity
2) 原生事件回调
onEvents((ev) => {
if (ev.eventType === 'roomConnected') {
// 连接成功事件中带有本地 identity
localIdentity.value = ev.payload?.localIdentity || ''
}
if (ev.eventType === 'localTrackSubscribed' && ev.payload?.trackKind === 'VIDEO') {
// 本地视频就绪,确保预览
localIdentity.value = ev.payload?.participantIdentity || localIdentity.value
}
})
3) 获取房间参与者接口
const res = await getRoomParticipants()
localIdentity.value = res?.data?.localParticipant?.participantIdentity || ''
传值到组件(结合 v-if 控制):
<livekit-video-view
v-if="cameraEnabled && !!localIdentity"
key="local"
style="width: 300px; height: 200px"
:localIdentity="localIdentity"
/>
如何获取并传递 remoteIdentity
获取途径:
1) 快照接口(连接成功后立即刷新)
const res = await getRoomParticipants()
const remotes = Array.isArray(res?.data?.remoteParticipants) ? res.data.remoteParticipants : []
// 组装远端渲染列表:优先使用 identity,缺失时回退为 sid
remoteViews.value = remotes
.map((p) => {
const id = p.participantIdentity || p.participantSid || ''
const active = Array.isArray(p.tracks)
? p.tracks.some((t) => t.kind === 'VIDEO' && t.subscribed === true && t.muted !== true)
: false
return id ? { id, active } : null
})
.filter(Boolean)
2) 原生事件驱动(实时维护 active 状态)
onEvents(async (ev) => {
switch (ev.eventType) {
case 'participantConnected':
case 'participantDisconnected':
case 'trackPublished':
case 'trackUnpublished':
case 'trackSubscribed':
case 'trackUnsubscribed':
case 'trackMuted':
case 'trackUnmuted': {
// 这些事件都会影响远端是否“可渲染”,统一刷新一次
await updateIdentitiesAfterConnect()
break
}
}
})
传值到组件(结合 v-if 与 v-for):
<view class="remote-grid">
<view class="remote-item" v-for="rv in remoteViews" :key="rv.id">
<livekit-video-view
v-if="rv.active"
style="width: 300px; height: 200px"
:remoteIdentity="rv.id"
/>
</view>
</view>
完整示例(页面片段)
<view class="rtc-section">
<text class="section-title">RTC 预览:</text>
<livekit-video-view
v-if="cameraEnabled && !!localIdentity"
key="local"
style="width: 300px; height: 200px"
:localIdentity="localIdentity"
/>
<view class="remote-grid">
<view class="remote-item" v-for="rv in remoteViews" :key="rv.id">
<livekit-video-view
v-if="rv.active"
style="width: 300px; height: 200px"
:remoteIdentity="rv.id"
/>
</view>
</view>
</view>
注意事项
- 必须先调用
initRoom()并注册onEvents(),再调用connectToRoom(),以避免丢失连接早期事件。 - 组件仅负责“渲染器挂载/释放”,业务层需根据轨道状态维护
cameraEnabled与远端的active。
提示
- 在开发iOS 时 CocoaPods 拉取镜像可能遇到超时或缓慢问题,推荐挂vpn开启全局代理取保网络正常。
- iOS发布时在
app-ios/Info.plist需删除允许所有明文 HTTP、WebSocket 请求iOS官方建议只采用HTTPS访问。

收藏人数:
购买源码授权版(
试用
使用 HBuilderX 导入示例项目
赞赏(0)
下载 0
赞赏 0
下载 12562947
赞赏 1949
赞赏
京公网安备:11010802035340号