腾讯云实时音视频(TRTC)是目前国内企业直播、在线教育、医疗问诊等场景中使用最广泛的实时音视频底层服务之一。很多企业在选型后会面临一个问题:SDK怎么集成到我们自己的系统里?
本文从实操角度,覆盖三种最主流的集成场景,附可直接复制使用的代码示例。
一、集成前准备:开通TRTC服务
步骤1:腾讯云实名认证
登录 腾讯云官网,完成个人或企业实名认证。未实名账号无法开通TRTC服务。
步骤2:创建TRTC应用
进入「云产品」→「实时音视频」→「应用管理」→「创建应用」,填写应用名称(通常用产品名),获取 SDKAppID。
步骤3:获取密钥
在「应用信息」页面,找到「密钥」模块。TRTC使用对称加密(UserSig机制),需要SecretKey生成用户签名。
⚠️ SecretKey是高度敏感信息,不要硬编码在前端代码里,必须放在后端服务器生成签名。
二、Web端集成(Vue3 + TRTC Web SDK)
2.1 安装依赖
npm install trtc-js-sdk --save
2.2 核心代码:创建客户端并加入房间
import TRTCCloud from 'trtc-js-sdk';
// 创建TRTC客户端实例
const trtc = TRTCCloud.create({
sdkAppId: 1400000000, // 替换为你的SDKAppID
userId: 'user_' + Math.random().toString(36).substr(2, 8),
userSig: '', // 由后端生成,前端不要硬编码
sessionId: 'page_live',
role: 'anchor', // anchor=主播,audience=观众
});
// 监听事件
trtc.on(TRTCCloud.EVENT.LOCAL_VIDEO_VIEWReady, () => {
console.log('本地视频已就绪');
});
trtc.on(TRTCCloud.EVENT.ERROR, (e) => {
console.error('TRTC错误:', e);
});
// 加入房间
trtc.enterRoom({ roomId: 123456 }).then(() => {
console.log('成功进入房间');
// 启动本地预览
trtc.startLocalVideo();
}).catch((err) => {
console.error('进入房间失败:', err);
});
2.3 推流核心代码
// 开始推流(将本地音视频发布到房间)
trtc.startLocalAudio().catch((err) => {
console.error('开启麦克风失败:', err);
});
// 订阅远端用户
trtc.on(TRTCCloud.EVENT.REMOTE_USER_ENTER, (userId) => {
console.log('远端用户加入:', userId);
// 自动订阅
trtc.subscribeRemoteUser(userId);
});
trtc.on(TRTCCloud.EVENT.REMOTE_VIDEO_VIEW_READY, (userId) => {
console.log('远端用户视频就绪:', userId);
// 将远端视频渲染到页面
const remoteView = trtc.createRemoteView(userId);
document.getElementById('remote-container').appendChild(remoteView);
remoteView.start({ userId, streamType: TRTCCloud.STREAM_TYPE.VIDEO });
});
2.4 退出房间
// 离开房间时调用
trtc.exitRoom().then(() => {
console.log('成功离开房间');
trtc.destroy();
}).catch((err) => {
console.error('离开房间异常:', err);
});
⚠️ Web端注意:TRTC Web SDK需要HTTPS环境(即使是localhost也需特殊配置)。开发阶段可使用
http://localhost,但生产环境必须是HTTPS。可使用nginx配置SSL证书。
三、微信小程序集成(TRTC插件方式)
3.1 开通小程序直播资质
在微信公众平台 → 「直播」 → 「直播组件」申请开通。需要:
- 已认证的小程序主体(企业认证)
- 类目符合《微信小程序直播功能准入要求》
- 近半年无严重违规记录
3.2 插件方式集成
在 project.config.json 中声明插件:
{
"plugins": {
"tencentcloud-trtc": {
"provider": "wxapkg2c9xxxxxx",
"version": "1.0.0"
}
}
}
3.3 推流核心代码(小程序)
// pages/live/live.js
const TRTC = requirePlugin('tencentcloud-trtc').plugin;
Page({
data: {
pusherContext: null,
roomId: 123456,
userId: 'user_' + Math.random().toString(36).substr(2, 8),
},
onLoad() {
this.initTRTC();
},
initTRTC() {
const pusher = wx.createLivePusherContext();
this.setData({ pusherContext: pusher });
// 监听推流事件
pusher.onPush((e) => {
if (e.detail.code === 200) {
console.log('推流成功');
} else {
console.error('推流失败:', e.detail);
}
});
},
startPush() {
// 页面中需要有 <live-pusher> 组件
this.data.pusherContext.start();
},
stopPush() {
this.data.pusherContext.stop();
},
})
3.4 页面wxml结构
<!-- pages/live/live.wxml -->
<live-pusher
url="{{pushUrl}}"
mode="RTC"
autopush="{{true}}"
bind:pushstatus="onPushStatus"
style="width:100%;height:300px;"
/>
<!-- 拉流列表 -->
<view wx:for="{{remoteUsers}}" wx:key="userId">
<live-player
src="{{item.url}}"
mode="RTC"
autoplay="{{true}}"
style="width:100%;height:200px;"
/>
</view>
四、uni-app集成(腾讯云TRTC插件)
uni-app 集成TRTC有两种方式:通过插件市场的插件,或使用腾讯云原生SDK(uni-app nvue 页面)。推荐使用插件方式,集成更快。
4.1 插件安装
在 HBuilderX → 插件市场 → 搜索「腾讯云TRTC」→ 安装到项目。
4.2 App端推流核心代码
// App端推流
const TRTCCalling = uni.requireNativePlugin('GDT_TRTC');
export default {
data() {
return {
sdkAppId: 1400000000,
roomId: 123456,
userId: 'user_' + Math.random().toString(36).substr(2, 8),
}
},
methods: {
startLive() {
TRTCCalling.createTRTCInstance({
sdkAppId: this.sdkAppId,
});
TRTCCalling.enterRoom({
roomId: this.roomId,
userId: this.userId,
userSig: this.getUserSigFromServer(), // 后端获取
role: 'anchor',
}, (res) => {
console.log('进入房间成功', res);
// 开启本地预览
TRTCCalling.startLocalPreview();
});
},
getUserSigFromServer() {
// ⚠️ 必须从后端接口获取,这里是示意代码
// 真实场景:uni.request({ url: 'YOUR_SERVER/api/getUserSig' })
return '';
},
}
}
五、TRTC常见错误码及解决方案
⚠️ 高频错误码
-1003:签名验证失败 — 检查userSig是否正确生成,secretKey是否匹配-1006:房间进入失败 — 房间ID是否存在,roomId类型是否为number-1007:SDKAppID不匹配 — 确认前端SDKAppID与控制台创建的一致-1021:网络超时 — 检查服务器与TRTC接入点的网络延迟-1022:进房超时 — 通常是跨地域接入问题,可尝试配置就近接入-1004:TRTC服务未开通 — 去腾讯云控制台开通服务-7001:userSig已过期 — userSig有效期默认24小时,重新从后端获取
六、自建后端生成UserSig(Node.js示例)
UserSig必须放在后端生成,以下是Node.js示例:
// server/genUserSig.js
const crypto = require('crypto');
function genUserSig(sdkAppId, secretKey, userId, EXPIRE_TIME = 86400 * 180) {
const now = Math.floor(Date.now() / 1000);
const param = {
"ver": "1.0",
"SdkAppId": sdkAppId,
"UserId": userId,
"Time": now,
"ExpireTime": now + EXPIRE_TIME,
};
const json = JSON.stringify(param);
const compressed = Buffer.from(json).toString('base64');
const signature = crypto
.createHmac('sha256', secretKey)
.update(compressed)
.digest('hex');
return Buffer.from(JSON.stringify({
signature: signature,
t: now,
expireTime: now + EXPIRE_TIME,
})).toString('base64');
}
module.exports = genUserSig;