企业级直播系统在技术选型完成后,面对的第一个实际问题就是SDK怎么集成到现有系统里。Web端(Vue/React)、微信小程序、App端(uni-app)各有不同的集成方式和坑点,选错方案可能导致反复返工。
VideoTV 基于大量企业直播项目经验,整理了三端集成的完整实操指南。无论你的技术栈是Web前端、小程序还是混合App,都能在此找到可直接复制使用的代码示例。
一、集成前准备:开通实时音视频服务
步骤1:云平台实名认证
登录云服务商控制台,完成企业实名认证。未认证的账号无法开通实时音视频服务。
步骤2:创建直播应用
进入「云产品」→「实时音视频」→「应用管理」→「创建应用」,填写应用名称(通常用产品名),获取 SDKAppID。
步骤3:获取密钥
在「应用信息」页面,找到「密钥」模块。直播SDK使用对称加密机制,需要SecretKey来生成用户签名(UserSig)。
⚠️ SecretKey是高度敏感信息,不要硬编码在前端代码里,必须放在后端服务器生成签名。
二、Web端集成(Vue3 + 直播SDK)
2.1 安装依赖
npm install trtc-js-sdk --save
2.2 核心代码:创建客户端并加入房间
import TRTCCloud from 'trtc-js-sdk';
const client = TRTCCloud.create({
sdkAppId: 1400000000,
userId: 'user_' + Math.random().toString(36).substr(2, 8),
userSig: '',
sessionId: 'page_live',
role: 'anchor',
});
client.on(TRTCCloud.EVENT.LOCAL_VIDEO_VIEWReady, () => {
console.log('本地视频已就绪');
});
client.on(TRTCCloud.EVENT.ERROR, (e) => {
console.error('SDK错误:', e);
});
client.enterRoom({ roomId: 123456 }).then(() => {
console.log('成功进入房间');
client.startLocalVideo();
}).catch((err) => {
console.error('进入房间失败:', err);
});
2.3 推流核心代码
client.startLocalAudio().catch((err) => {
console.error('开启麦克风失败:', err);
});
client.on(TRTCCloud.EVENT.REMOTE_USER_ENTER, (userId) => {
console.log('远端用户加入:', userId);
client.subscribeRemoteUser(userId);
});
client.on(TRTCCloud.EVENT.REMOTE_VIDEO_VIEW_READY, (userId) => {
console.log('远端用户视频就绪:', userId);
const remoteView = client.createRemoteView(userId);
document.getElementById('remote-container').appendChild(remoteView);
remoteView.start({ userId, streamType: TRTCCloud.STREAM_TYPE.VIDEO });
});
2.4 退出房间
client.exitRoom().then(() => {
console.log('成功离开房间');
client.destroy();
}).catch((err) => {
console.error('离开房间异常:', err);
});
⚠️ Web端注意:直播SDK的Web端需要HTTPS环境(即使是localhost也需特殊配置)。开发阶段可使用
http://localhost,但生产环境必须是HTTPS。VideoTV 推荐使用nginx配置SSL证书,确保推流稳定。
三、微信小程序集成(直播插件方式)
3.1 开通小程序直播资质
在微信公众平台 → 「直播」 → 「直播组件」申请开通。需要:
- 已认证的小程序主体(企业认证)
- 类目符合《微信小程序直播功能准入要求》
- 近半年无严重违规记录
3.2 插件方式集成
在 project.config.json 中声明插件:
{
"plugins": {
"live-player-plugin": {
"provider": "wxapkg2c9xxxxxx",
"version": "1.0.0"
}
}
}
3.3 推流核心代码(小程序)
const plugin = requirePlugin('live-player-plugin');
Page({
data: {
pusherContext: null,
roomId: 123456,
userId: 'user_' + Math.random().toString(36).substr(2, 8),
},
onLoad() { this.initLive(); },
initLive() {
const pusher = wx.createLivePusherContext();
this.setData({ pusherContext: pusher });
pusher.onPush((e) => {
if (e.detail.code === 200) console.log('推流成功');
else console.error('推流失败:', e.detail);
});
},
startPush() { this.data.pusherContext.start(); },
stopPush() { this.data.pusherContext.stop(); },
})
3.4 页面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集成(跨端直播方案)
uni-app 集成直播能力有两种方式:通过插件市场的直播插件,或使用原生SDK(uni-app nvue 页面)。对于大多数团队,推荐插件方式,集成更快、维护成本低。
4.1 插件安装
在 HBuilderX → 插件市场 → 搜索「直播插件」→ 安装到项目。
4.2 App端推流核心代码
const LiveModule = uni.requireNativePlugin('GDT_Live');
export default {
data() {
return {
sdkAppId: 1400000000,
roomId: 123456,
userId: 'user_' + Math.random().toString(36).substr(2, 8),
}
},
methods: {
startLive() {
LiveModule.createInstance({ sdkAppId: this.sdkAppId });
LiveModule.enterRoom({
roomId: this.roomId,
userId: this.userId,
userSig: this.getUserSigFromServer(),
role: 'anchor',
}, (res) => {
console.log('进入房间成功', res);
LiveModule.startLocalPreview();
});
},
getUserSigFromServer() {
// ⚠️ 必须从后端接口获取
return '';
},
}
}
五、常见集成错误码及解决方案
⚠️ 高频错误码
-1003:签名验证失败 — 检查userSig是否正确生成,secretKey是否匹配-1006:房间进入失败 — 房间ID是否存在,roomId类型是否为number-1007:SDKAppID不匹配 — 确认前端SDKAppID与控制台创建的一致-1021:网络超时 — 检查服务器与直播服务接入点的网络延迟-1022:进房超时 — 通常是跨地域接入问题,可尝试配置就近接入-1004:直播服务未开通 — 去云服务控制台开通实时音视频服务-7001:userSig已过期 — userSig有效期默认24小时,重新从后端获取
六、自建后端生成UserSig(Node.js示例)
UserSig必须在后端生成以保障安全,以下是Node.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, t: now, expireTime: now + EXPIRE_TIME,
})).toString('base64');
}
module.exports = genUserSig;
相关阅读
- 《电商直播系统搭建完整指南》 — 电商直播全攻略
- 《企业直播平台多少钱?2026年价格体系解读》 — 直播成本怎么算
- 《企业直播平台选型指南:避开这5个坑》 — 选平台防坑