更新记录
1.0.4(2026-12-02)
- 拉流组件播放器实例与 observer 改为绑定组件实例(不再模块级全局共用),
NVUnloaded与unmounted均完整销毁:解绑 observer → 音量归零 → stopPlay → 置空,修复退出页面仍有声音、再进页面复用失效实例导致闪退 - 对外
stopPlay()改为走同一套完整销毁 - 拉流组件新增
minCache/maxCache属性(默认 0.3 / 0.8 秒),startPlay前设置缓存以降低互动直播延迟
1.0.3(2026-12-02)
对接官方 snapshot 截图(base64 事件返回)及播放器常用接口;新增 @volume 事件
1.0.2(2026-12-02)
- 修复 Xcode 27 编译失败:iOS 插件
deploymentTarget提升至 15.0 - iOS 移除 CocoaPods 依赖(TXLiteAVSDK_Live 的 podspec 固定 iOS 8.0,新版 Xcode 直接报错),改用插件内置的 TXLiteAVSDK_Professional.framework
平台兼容性
uni-app(4.62)
| Vue2 | Vue3 | Chrome | Safari | app-vue | app-nvue | Android | iOS | 鸿蒙 |
|---|---|---|---|---|---|---|---|---|
| √ | √ | - | - | - | - | - | - | - |
| 微信小程序 | 支付宝小程序 | 抖音小程序 | 百度小程序 | 快手小程序 | 京东小程序 | 鸿蒙元服务 | QQ小程序 | 飞书小程序 | 小红书小程序 | 快应用-华为 | 快应用-联盟 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| - | - | - | - | - | - | - | - | - | - | - | - |
uni-app x(5.21)
| Chrome | Safari | Android | iOS | 鸿蒙 | 微信小程序 | 支付宝小程序 |
|---|---|---|---|---|---|---|
| - | - | - | - | - | - | - |
其他
| 多语言 | 暗黑模式 | 宽屏模式 | 蒸汽模式 |
|---|---|---|---|
| × | × | × | √ |
tencentcloud-liteav · 腾讯云直播(推流 / 拉流)UTS 插件
基于 腾讯云 LiteAVSDK(V2TXLive) 二次封装的 uni-app UTS 组件插件(uni-app 兼容模式,面向 nvue 页面)。Android 用 LiteAVSDK_Live aar,iOS 直接用插件内置的 TXLiteAVSDK_Professional.framework(无 CocoaPods)。 提供「主播推流」与「观众拉流」两个全局组件,开箱即用,一套代码双端(Android / iOS)运行。
特性
- 直播推流:RTMP 推流、自动开相机/麦克风、切前后摄、闪光灯、美颜、静音
- 直播拉流:FLV / RTMP / LEB(WebRTC) 播放、暂停/恢复、铺满/完整切换、静音
- ⚡ 事件驱动:所有结果(成功/失败/状态/网速)都通过
@statechange/@netstatus回调,任何操作必有回调(含 SDK 同步失败的主动 error 上报) - 免 CocoaPods:iOS 直接使用插件内置 framework,不再执行 pod install,规避第三方 pod 最低版本与新版 Xcode 的冲突
- 纯 UTS:无 requireNativePlugin 依赖、无遗留 JS 桥接,直接编译为原生(Kotlin / Swift)
一、快速接入
1. 安装插件
将 uni_modules/tencentcloud-liteav 目录放入项目 uni_modules/ 下(HBuilderX 导入本地插件目录亦可)。
2. 申请 License
腾讯云控制台 → 云直播/移动直播 → 申请(或测试)License,得到一对:
licenseUrl(形如https://xxx/license/v2/<AppId>_1/v_cube.license)licenseKey
⚠️ License 按应用包名绑定:Android 绑 applicationId、iOS 绑 Bundle ID。调试基座的包名也必须与 License 绑定的包名一致,否则推/拉流返回
-5。
3. 注册 License(推/拉流前调用一次)
// 建议放 App.vue onLaunch;也可在页面 startPush/startPlay 前调用
import { setLicence } from '@/uni_modules/tencentcloud-liteav'
setLicence({
licenseUrl: 'https://your.license.url/v_cube.license',
licenseKey: 'your-license-key'
})
⚠️
setLicence只是「注册」,同步返回、不做校验。License 是否有效,以首次startPush/startPlay的返回(@statechange事件)为准:收到error code=-5即为「License 无效或包名不匹配」。
4. 相机 / 麦克风权限
- Android:插件已声明权限;运行期需页面主动请求运行时权限。App 端不能使用
uni.authorize(仅小程序端支持),请用plus.android.requestPermissions(['android.permission.CAMERA','android.permission.RECORD_AUDIO'], cb, err)(详见下方示例)。 - iOS:插件
info.plist已含用途描述,首次推流时系统自动弹框授权;若曾被拒绝,需在系统设置 → 隐私与安全性 → 相机/麦克风手动开启。
5. 自定义基座(必须)
UTS 插件编译为原生代码,标准基座不含,调试/打包必须走自定义基座:
- 调试:HBuilderX → 运行 → 运行到手机或模拟器 → 制作自定义调试基座
- 发布:云打包 / 离线打包(自动携带插件原生代码)
二、页面使用(nvue)
组件为 uni-app 兼容模式 UTS 组件,全局注册,模板直接使用标签;必须设置宽高。示例(推流 + 观看同页):
<template>
<!-- ============ 外层:整页可滚动 ============ -->
<scroll-view class="page" scroll-y="true" show-scrollbar="false">
<view class="container">
<!-- ============ 顶部标题 ============ -->
<view class="hero">
<text class="hero-title">腾讯云直播调试台</text>
<text class="hero-sub">推流 Pusher + 播放 Player · 单页联调 · uni_modules/tencentcloud-liteav</text>
</view>
<!-- ============ 卡片 1:License 激活 ============ -->
<view class="card">
<view class="card-head">
<text class="card-title">① License</text>
<text class="lic-pill" :class="licTone">{{ licenceState }}</text>
</view>
<button class="btn btn-accent" @click="initLicense">注册并探测 License</button>
<text class="hint">提示:setLicence 只注册不校验,真伪以「开始推流/播放」返回码为准(-5=License无效或包名不匹配)。</text>
</view>
<!-- ============ 卡片 2:相机/麦克风权限 ============ -->
<view class="card">
<view class="card-head">
<text class="card-title">② 设备权限</text>
</view>
<button class="btn btn-violet" @click="grantPermission">📷 授权相机 / 麦克风(推流必需)</button>
<text class="hint">Android 6+ 需运行时授权;iOS 首次推流系统自动弹框,曾拒绝需到 系统设置→应用 手动开启。</text>
</view>
<!-- ============ 卡片 3:主播推流 ============ -->
<view class="card">
<view class="card-head">
<text class="card-title">③ 主播推流</text>
<text class="tag">tencentcloud-pusher</text>
</view>
<tencentcloud-pusher ref="pusher" class="stage" @statechange="onPusherState"
@netstatus="onPusherNet" @snapshot="onPusherSnapshot"></tencentcloud-pusher>
<text class="net" v-if="lastPusherNet">📶 推流 {{ lastPusherNet }}</text>
<view class="btn-row">
<button class="btn btn-accent cell" @click="startPush">开始推流</button>
<button class="btn cell" @click="stopPush">停止</button>
<button class="btn cell" @click="switchCamera">切摄像头</button>
</view>
<view class="btn-row">
<button class="btn cell cell-half" @click="toggleFlash">{{ flashOn ? '关闪光' : '开闪光' }}</button>
<button class="btn cell cell-half" @click="togglePusherMute">{{ pusherMute ? '恢复声音' : '静音' }}</button>
</view>
<view class="btn-row">
<button class="btn cell" @click="pushSnapshot">📸 截图</button>
<button class="btn cell" @click="togglePushVideo">{{ pushVideoOn ? '暂停视频' : '恢复视频' }}</button>
<button class="btn cell" @click="setBeauty">💄 美颜</button>
</view>
</view>
<!-- ============ 卡片 4:观众观看 ============ -->
<view class="card">
<view class="card-head">
<text class="card-title">④ 观众观看</text>
<text class="tag">tencentcloud-player</text>
</view>
<tencentcloud-player ref="player" class="stage" @statechange="onPlayerState"
@netstatus="onPlayerNet" @snapshot="onPlayerSnapshot" @volume="onVolume"></tencentcloud-player>
<text class="net" v-if="lastPlayNet">📶 观看 {{ lastPlayNet }}</text>
<view class="btn-row">
<button class="btn btn-accent cell" @click="startPlay">开始播放</button>
<button class="btn cell" @click="stopPlay">停止</button>
<button class="btn cell" @click="pausePlay">暂停</button>
</view>
<view class="btn-row">
<button class="btn cell" @click="resumePlay">恢复</button>
<button class="btn cell" @click="changeRenderMode">{{ renderMode === 0 ? '铺满' : '完整' }}</button>
<button class="btn cell" @click="togglePlayerMute">{{ playerMute ? '恢复声音' : '静音' }}</button>
</view>
<view class="btn-row">
<button class="btn cell" @click="playSnapshot">📸 截图</button>
<button class="btn cell" @click="toggleAudioTrack">{{ audioTrackOn ? '暂停音频' : '恢复音频' }}</button>
<button class="btn cell" @click="toggleVideoTrack">{{ videoTrackOn ? '暂停视频' : '恢复视频' }}</button>
</view>
</view>
<!-- ============ 卡片 5:播放器增强 ============ -->
<view class="card">
<view class="card-head">
<text class="card-title">⑤ 播放器增强</text>
<text class="tag">新增接口 · volume / mirror / SEI / stream</text>
</view>
<view class="btn-row">
<button class="btn cell" @click="probePlaying">🔍 查询状态</button>
<button class="btn cell" @click="toggleVolumeEval">{{ volumeEvalOn ? '关音量评估' : '开音量评估' }}</button>
<button class="btn cell" @click="toggleDebug">{{ debugOn ? '关调试层' : '开调试层' }}</button>
</view>
<view class="btn-row">
<button class="btn cell" @click="toggleMirror">{{ mirrorOn ? '关镜像' : '开镜像' }}</button>
<button class="btn cell" @click="toggleVolume">{{ playVolume === 100 ? '音量50' : '音量100' }}</button>
<button class="btn cell" @click="toggleSei">{{ seiOn ? '关SEI' : '收SEI' }}</button>
</view>
<view class="btn-row">
<input class="ipt ipt-inline" placeholder="备用流地址(切换用)" v-model="altPlayUrl" />
<button class="btn cell" @click="switchStream">🔀 切流</button>
</view>
<text class="hint">开启音量评估后实时音量走 @volume 事件(见下方日志);SEI 需业务流携带 payloadType 5/242/243,这里用 242。</text>
<!-- 截图预览 -->
<view class="snap-box">
<image v-if="snapSrc" class="snap-img" :src="snapSrc" mode="aspectFit"></image>
<text v-else class="snap-ph">📸 点「截图」后在此预览(推流 / 播放共用)</text>
</view>
<text class="net" v-if="snapInfo">{{ snapInfo }}</text>
<button v-if="snapB64" class="btn btn-accent cell-save" @click="saveSnapshot">💾 保存到相册</button>
</view>
<!-- ============ 日志区:固定高度可滑动 ============ -->
<view class="card log-card">
<view class="card-head">
<text class="card-title">⑥ 事件日志</text>
<text class="tag">最新 20 条 · 可上下滑动</text>
</view>
<scroll-view class="log-scroll" scroll-y="true" show-scrollbar="false">
<view class="log-line" :class="log.cls" v-for="(log, idx) in logs" :key="idx">
<text class="log-time">{{ log.t }}</text>
<text class="log-msg">{{ log.text }}</text>
</view>
</scroll-view>
</view>
</view>
</scroll-view>
</template>
<script>
/**
* 腾讯云直播单页调试台(推流 + 观看)
*
* 设计约定:
* - trace(msg, raw):所有操作/回调的唯一输出口 —— 页面日志区 + 控制台([wbLive] 前缀),raw 输出事件原始 JSON
* - 组件方法无回调,结果统一走 @statechange 事件(含 SDK 同步失败的主动 error 上报)
* - 事件数据为 Map<string,any>,经 normEvent 归一化(兼容 e.detail / Map / 普通对象)
* - 推流需相机/麦克风权限:Android 用 plus.android.requestPermissions,iOS 系统自动弹框
* - 需要自定义基座运行(UTS 插件为原生编译,标准基座不含)
*/
// #ifdef APP-PLUS
import { setLicence } from '@/uni_modules/tencentcloud-liteav'
// #endif
export default {
data() {
return {
/* ---------- 配置区(页面可直接编辑) ---------- */
// 腾讯云移动直播 License(控制台申请,需与应用包名匹配;-5 即不匹配)
licenseUrl: 'https://xxxve.xxxve.cn/xxxve/xxxve/xxxve/v_cube.license',
licenseKey: 'xxxve',
pushUrl: "rtmp://xxxve/live/app?txSecret=xxxve&txTime=xxxve",
playUrl: "https://xxxve/app.flv",
/* ---------- 运行状态 ---------- */
licenceState: '未配置',
pusherMute: false,
playerMute: false,
flashOn: false,
renderMode: 0,
lastPusherNet: '',
lastPlayNet: '',
/* ---------- 新增功能状态 ---------- */
pushVideoOn: true, // 推流视频轨:true 播放中
audioTrackOn: true, // 播放音频轨
videoTrackOn: true, // 播放视频轨
volumeEvalOn: false, // 音量评估开关
debugOn: false, // 调试浮层
mirrorOn: false, // 播放镜像
seiOn: false, // SEI 接收开关
playVolume: 100, // 播放音量 0-100
altPlayUrl: '', // 备用流地址(切流用)
snapSrc: '', // 截图预览 data:image/png;base64,...
snapB64: '', // 纯 base64(已去换行),供保存到相册用
snapInfo: '', // 截图信息(尺寸/来源)
lastVolume: 0, // 最近一次 @volume 音量
logs: []
}
},
onReady() {
this.trace('=== 页面就绪(UTS 直播插件)===');
this.initLicense();
this.grantPermission();
this._checkComponents();
},
computed: {
/* License 状态 → 徽标颜色 */
licTone() {
const s = this.licenceState;
if (s.indexOf('无效') > -1 || s.indexOf('❌') > -1) return 'tone-danger';
if (s.indexOf('异常') > -1) return 'tone-warn';
if (s.indexOf('已') > -1 || s.indexOf('✅') > -1) return 'tone-ok';
return 'tone-mute';
}
},
methods: {
/* ================= ① 日志输出(唯一出口) ================= */
trace(msg, raw) {
const t = new Date().toLocaleTimeString();
let cls = '';
if (msg.indexOf('❌') === 0) cls = 'err';
else if (msg.indexOf('⚠️') === 0) cls = 'warn';
else if (msg.indexOf('✅') > -1 || msg.indexOf('成功') > -1) cls = 'ok';
this.logs.unshift({ t, text: msg, cls });
if (this.logs.length > 20) this.logs.pop();
console.log('[wbLive]', msg);
if (raw !== undefined) console.log('[wbLive] raw =', raw);
},
/* ================= ② 生命周期内组件自检 ================= */
_checkComponents() {
const pusherOk = this.$refs.pusher && typeof this.$refs.pusher.startPush === 'function';
const playerOk = this.$refs.player && typeof this.$refs.player.startPlay === 'function';
const newApi = this.$refs.player && typeof this.$refs.player.snapshot === 'function';
this.trace(`[组件检测] pusher=${pusherOk ? '✅' : '❌'} | player=${playerOk ? '✅' : '❌'} | 新增接口=${newApi ? '✅ 已生效' : '❌ 需重做基座'}`);
},
/* ================= ③ License(注册 + 可达性探测 + 返回码回写) ================= */
initLicense() {
if (!this.licenseUrl || !this.licenseKey) {
this.licenceState = '未配置';
this.trace('⚠️ License 未配置,推拉流可能报 -5');
return;
}
try {
setLicence({ licenseUrl: this.licenseUrl, licenseKey: this.licenseKey });
this.licenceState = '已注册·待校验';
this.trace('✅ setLicence 已注册(真伪看推流/播放返回码,-5=无效)');
} catch (e) {
this.licenceState = '注册异常';
this.trace('❌ setLicence 异常: ' + (e && e.message ? e.message : e));
}
// 可达性探测:HTTP 200 = 文件可下载(不代表 key/包名匹配)
uni.request({
url: this.licenseUrl,
method: 'GET',
success: (r) => {
this.trace(`🌐 License 服务: HTTP ${r.statusCode} ${r.statusCode === 200 ? '✅ 可下载' : '⚠️ 异常'}`);
},
fail: (e) => {
this.trace('⚠️ License 服务不可达:' + (e && e.errMsg ? e.errMsg : JSON.stringify(e)));
}
});
},
_markLicenceByCode(code) {
if (code === -5) this.licenceState = '无效(-5 包名/License)';
},
/* ================= ④ 相机/麦克风运行时权限 ================= */
grantPermission() {
const platform = uni.getSystemInfoSync().platform;
this.trace('📱 平台: ' + platform);
if (platform === 'ios') {
this.trace('ℹ️ iOS 无需手动授权,首次推流时系统自动弹框');
return;
}
if (typeof plus === 'undefined' || !plus.android || typeof plus.android.requestPermissions !== 'function') {
this.trace('❌ 无 plus.android.requestPermissions,请到 系统设置→wbLive→权限 手动开启');
return;
}
this.trace('📷 请求相机/麦克风权限…');
plus.android.requestPermissions(
['android.permission.CAMERA', 'android.permission.RECORD_AUDIO'],
(res) => {
const dp = res.deniedPresent || [];
const da = res.deniedAlways || [];
this.trace(`[权限] granted=${JSON.stringify(res.granted)} 拒绝=${JSON.stringify(dp)} 永久=${JSON.stringify(da)}`);
if (dp.length === 0 && da.length === 0) this.trace('✅ 相机/麦克风均已授权');
else if (da.length > 0) this.trace('❌ 已被永久拒绝:' + da.join(',') + ',需到系统设置手动开启');
else this.trace('❌ 本次被拒绝:' + dp.join(',') + ',可重试');
},
(err) => {
this.trace('❌ 权限请求失败:' + (err && err.message ? err.message : JSON.stringify(err)));
}
);
},
/* ================= ⑤ 工具:事件/网络状态归一化 ================= */
normEvent(e) {
// Map → 普通对象(Android 事件参数本来就是 Map;iOS 内层 detail 也可能是 Map)
const toObj = (v) => {
if (v && typeof v === 'object' && typeof v.get === 'function') {
const o = {};
try { v.forEach((val, k) => { o[k] = val; }); } catch (err) { }
return o;
}
return v;
};
let d = e;
if (e && typeof e === 'object') {
if (e.detail !== undefined) {
d = toObj(e.detail);
// iOS UTS 兼容组件:插件侧按官方建议包了一层 detail,个别基座会出现 detail.detail 两层壳
if (d && typeof d === 'object' && d.detail !== undefined) {
const inner = toObj(d.detail);
if (inner && typeof inner === 'object') d = inner;
}
} else {
d = toObj(e);
}
if (d && typeof d === 'object') return d;
return { value: d };
}
return { value: d };
},
evtText(e) {
try { return JSON.stringify(this.normEvent(e)); } catch (err) { return String(e); }
},
netText(obj) {
if (!obj) return '';
const p = [];
if (obj.fps !== undefined) p.push('fps=' + obj.fps);
if (obj.videoBitrate !== undefined) p.push('video=' + obj.videoBitrate);
if (obj.audioBitrate !== undefined) p.push('audio=' + obj.audioBitrate);
if (obj.rtt !== undefined) p.push('rtt=' + obj.rtt);
if (obj.netSpeed !== undefined) p.push('net=' + obj.netSpeed);
if (obj.appCpu !== undefined) p.push('cpu=' + obj.appCpu);
return p.join(' ');
},
/* ================= ⑥ 推流端 ================= */
_checkPusher() {
if (!this.$refs.pusher || typeof this.$refs.pusher.startPush !== 'function') {
this.trace('❌ pusher 组件不可用,请确认自定义基座');
return false;
}
return true;
},
startPush() {
if (!this._checkPusher()) return;
// #ifdef APP-ANDROID
if (typeof plus !== 'undefined' && plus.android && typeof plus.android.requestPermissions === 'function') {
this.trace('🛡 推流前校验权限…');
plus.android.requestPermissions(
['android.permission.CAMERA', 'android.permission.RECORD_AUDIO'],
(res) => {
const denied = (res.deniedPresent || []).concat(res.deniedAlways || []);
if (denied.length === 0) this._doStartPush();
else this.trace('❌ 相机/麦克风未授权(' + denied.join(',') + ')');
},
() => this._doStartPush()
);
return;
}
// #endif
this._doStartPush();
},
_doStartPush() {
try {
this.trace('➡️ 开始推流: ' + this.pushUrl);
this.$refs.pusher.startPush(this.pushUrl);
this._armWatch('push');
} catch (e) {
this.trace('❌ startPush 异常:' + (e && e.message ? e.message : String(e)));
}
},
stopPush() {
if (!this._checkPusher()) return;
this.$refs.pusher.stopPush();
this.trace('⏹ 已停止推流');
},
switchCamera() {
if (!this._checkPusher()) return;
this.$refs.pusher.switchCamera();
this.trace('🔄 已切换摄像头');
},
toggleFlash() {
if (!this._checkPusher()) return;
this.flashOn = !this.flashOn;
this.$refs.pusher.turnOnFlash(this.flashOn);
this.trace(this.flashOn ? '🔦 闪光灯已开' : '🔦 闪光灯已关');
},
setBeauty() {
if (!this._checkPusher()) return;
this.$refs.pusher.setBeautyDepth({ beauty: 6, whitening: 5, ruddy: 2 });
this.trace('💄 已设置自然美颜');
},
togglePusherMute() {
if (!this._checkPusher()) return;
this.pusherMute = !this.pusherMute;
this.$refs.pusher.muteAudio(this.pusherMute);
this.trace(this.pusherMute ? '🔇 推流端静音' : '🎙 推流端恢复音频');
},
/* ---- 推流端新增:截图 / 视频轨 ---- */
pushSnapshot() {
if (!this._checkPusher()) return;
const code = this.$refs.pusher.snapshot();
this.trace(`📸 推流截图调用返回 code=${code}` + (code === 0 ? '(等待 @snapshot)' : ''));
},
togglePushVideo() {
if (!this._checkPusher()) return;
this.pushVideoOn = !this.pushVideoOn;
const code = this.pushVideoOn ? this.$refs.pusher.resumeVideo() : this.$refs.pusher.pauseVideo();
this.trace(`${this.pushVideoOn ? '▶️ 恢复' : '⏸ 暂停'}推流视频 code=${code}`);
},
onPusherSnapshot(e) {
this._applySnapshot(e, '推流');
},
onPusherState(e) {
this._markEvt('push');
const d = this.normEvent(e);
const type = d.type || '';
const msg = d.msg || '';
if (type === 'error') {
this._markLicenceByCode(d.code);
this.trace(`❌【推流错误】code=${d.code} ${msg}`, this.evtText(e));
} else if (type === 'warning') {
this.trace(`⚠️【推流警告】code=${d.code} ${msg}`, this.evtText(e));
} else if (type === 'pushStatus') {
const m = { disconnected: '未连接', connecting: '连接中…', connectSuccess: '推流成功 ✅', reconnecting: '断线重连…' };
this.trace(`📡【推流】${m[d.status] || d.status}`, this.evtText(e));
} else {
this.trace(`📡【推流事件】${type} ${msg}`, this.evtText(e));
}
},
onPusherNet(e) {
this._markEvt('push');
const d = this.normEvent(e);
this.lastPusherNet = this.netText(d);
console.log('[wbLive] 📶 推流网络 raw =', this.evtText(e));
},
/* ================= ⑦ 播放端 ================= */
_checkPlayer() {
if (!this.$refs.player || typeof this.$refs.player.startPlay !== 'function') {
this.trace('❌ player 组件不可用,请确认自定义基座');
return false;
}
return true;
},
startPlay() {
if (!this._checkPlayer()) return;
this.trace('➡️ 开始播放: ' + this.playUrl);
this.$refs.player.startPlay(this.playUrl);
this._armWatch('play');
},
stopPlay() {
if (!this._checkPlayer()) return;
this.$refs.player.stopPlay();
this.trace('⏹ 已停止播放');
},
pausePlay() {
if (!this._checkPlayer()) return;
this.$refs.player.pause();
this.trace('⏸ 已暂停');
},
resumePlay() {
if (!this._checkPlayer()) return;
this.$refs.player.resume();
this.trace('▶️ 已恢复');
},
changeRenderMode() {
if (!this._checkPlayer()) return;
this.renderMode = this.renderMode === 0 ? 1 : 0;
this.$refs.player.setRenderMode(this.renderMode);
this.trace(`🎞 画面:${this.renderMode === 0 ? '铺满(Fill)' : '完整(Fit)'}`);
},
togglePlayerMute() {
if (!this._checkPlayer()) return;
this.playerMute = !this.playerMute;
this.$refs.player.setMute(this.playerMute);
this.trace(this.playerMute ? '🔇 播放端静音' : '🔊 播放端恢复音量');
},
/* ---- 播放端新增:截图 / 音视频轨 ---- */
playSnapshot() {
if (!this._checkPlayer()) return;
const code = this.$refs.player.snapshot();
this.trace(`📸 播放截图调用返回 code=${code}` + (code === 0 ? '(等待 @snapshot)' : ''));
},
toggleAudioTrack() {
if (!this._checkPlayer()) return;
this.audioTrackOn = !this.audioTrackOn;
const code = this.audioTrackOn ? this.$refs.player.resumeAudio() : this.$refs.player.pauseAudio();
this.trace(`${this.audioTrackOn ? '▶️ 恢复' : '⏸ 暂停'}音频轨 code=${code}`);
},
toggleVideoTrack() {
if (!this._checkPlayer()) return;
this.videoTrackOn = !this.videoTrackOn;
const code = this.videoTrackOn ? this.$refs.player.resumeVideo() : this.$refs.player.pauseVideo();
this.trace(`${this.videoTrackOn ? '▶️ 恢复' : '⏸ 暂停'}视频轨 code=${code}`);
},
/* ---- 播放器增强 ---- */
probePlaying() {
if (!this._checkPlayer()) return;
const s = this.$refs.player.isPlaying();
this.trace(`🔍 isPlaying() = ${s}(1=播放中 0=已停止)`);
},
toggleVolumeEval() {
if (!this._checkPlayer()) return;
this.volumeEvalOn = !this.volumeEvalOn;
const code = this.$refs.player.enableVolumeEvaluation(this.volumeEvalOn ? 300 : 0);
this.trace(`${this.volumeEvalOn ? '✅ 开启' : '⏹ 关闭'}音量评估(300ms) code=${code}`);
},
toggleDebug() {
if (!this._checkPlayer()) return;
this.debugOn = !this.debugOn;
this.$refs.player.showDebugView(this.debugOn);
this.trace(this.debugOn ? '🐞 已显示调试浮层' : '🐞 已隐藏调试浮层');
},
toggleMirror() {
if (!this._checkPlayer()) return;
this.mirrorOn = !this.mirrorOn;
const code = this.$refs.player.setRenderMirrorMode(this.mirrorOn);
this.trace(`${this.mirrorOn ? '🪞 开镜像' : '🪞 关镜像'} code=${code}`);
},
toggleVolume() {
if (!this._checkPlayer()) return;
this.playVolume = this.playVolume === 100 ? 50 : 100;
const code = this.$refs.player.setPlayoutVolume(this.playVolume);
this.trace(`🔊 播放音量 → ${this.playVolume} code=${code}`);
},
toggleSei() {
if (!this._checkPlayer()) return;
this.seiOn = !this.seiOn;
const code = this.$refs.player.enableReceiveSeiMessage(this.seiOn, 242);
this.trace(`${this.seiOn ? '📨 开始接收' : '📨 停止接收'} SEI(payloadType=242) code=${code}`);
},
switchStream() {
if (!this._checkPlayer()) return;
const url = this.altPlayUrl || this.playUrl;
const code = this.$refs.player.switchStream(url);
this.trace(`🔀 切流 → ${url} code=${code}`);
},
/* ---- 截图 / 音量事件统一处理(推流与播放共用) ---- */
_applySnapshot(e, from) {
// 统一走 normEvent:Android 的 Map 事件 / iOS 包了一层 detail 的事件都在这里被解开
const d = this.normEvent(e);
const code = d.code;
const rawB64 = d.base64;
if (Number(code) === 0 && rawB64) {
// Android Base64.DEFAULT 每 76 字符插 \n,必须去掉,否则 data URI 与 loadBase64Data 都会失败
const b64 = String(rawB64).replace(/[\r\n]/g, '');
this.snapB64 = b64;
this.snapSrc = 'data:image/png;base64,' + b64;
const size = (d.width && d.height) ? `${d.width}×${d.height} ` : '';
this.snapInfo = `🖼 ${from}截图成功 ${size}· base64 ${b64.length} 字符(可存相册查看)`;
this.trace(`📸【${from}截图成功】${this.snapInfo}`);
} else {
// 诊断:把归一化后的结果打出,若仍为空说明原生事件参数未送达(需重做基座)
this.trace(`❌【${from}截图失败】code=${code === undefined ? 'undefined(事件无参数)' : code} ${d.msg || ''}`, this.evtText(e));
}
},
/* ---- 截图保存到相册:base64 → 原生 Bitmap → 本地 png → 相册 ---- */
saveSnapshot() {
if (!this.snapB64) {
this.trace('⚠️ 暂无截图,请先点「截图」');
return;
}
// #ifdef APP-PLUS
try {
const bitmap = new plus.nativeObj.Bitmap('snapshot_' + Date.now());
bitmap.loadBase64Data(this.snapB64, () => {
const fileName = 'snapshot_' + Date.now() + '.png';
// 保存到应用下的临时 png
bitmap.save('_doc/' + fileName, { overwrite: true }, (saveRes) => {
const path = (saveRes && saveRes.target) ? saveRes.target : ('_doc/' + fileName);
// 写入系统相册
uni.saveImageToPhotosAlbum({
filePath: path,
success: () => this.trace('✅ 截图已保存到系统相册'),
fail: (err) => this.trace('❌ 保存相册失败:' + (err && err.errMsg ? err.errMsg : JSON.stringify(err)))
});
bitmap.clear();
}, (e) => {
this.trace('❌ Bitmap 写文件失败:' + JSON.stringify(e));
bitmap.clear();
});
}, (e) => {
this.trace('❌ base64 解码失败:' + JSON.stringify(e));
});
} catch (err) {
this.trace('❌ 保存截图异常:' + (err && err.message ? err.message : String(err)));
}
// #endif
},
onPlayerSnapshot(e) {
this._applySnapshot(e, '播放');
},
onVolume(e) {
const d = this.normEvent(e);
this.lastVolume = d.volume;
this.trace(`🔊【实时音量】volume=${d.volume}`, this.evtText(e));
},
onPlayerState(e) {
this._markEvt('play');
const d = this.normEvent(e);
const type = d.type || '';
const msg = d.msg || '';
if (type === 'error') {
this._markLicenceByCode(d.code);
this.trace(`❌【播放错误】code=${d.code} ${msg}`, this.evtText(e));
} else if (type === 'warning') {
this.trace(`⚠️【播放警告】code=${d.code} ${msg}`, this.evtText(e));
} else if (type === 'connected') {
this.trace('🔗 已连接服务器', this.evtText(e));
} else if (type === 'videoLoading') {
this.trace('⏳ 加载视频…');
} else if (type === 'videoPlaying') {
this.trace('▶️ 视频播放中', this.evtText(e));
} else if (type === 'audioPlaying') {
this.trace('🔊 音频播放中');
} else {
this.trace(`📡【播放事件】${type} ${msg}`, this.evtText(e));
}
},
onPlayerNet(e) {
this._markEvt('play');
const d = this.normEvent(e);
this.lastPlayNet = this.netText(d);
console.log('[wbLive] 📶 播放网络 raw =', this.evtText(e));
},
/* ================= ⑧ 3 秒无回调哨兵(排查用) ================= */
_markEvt(kind) {
if (kind === 'push') this._pushEvt = true;
else this._playEvt = true;
},
_armWatch(kind) {
if (kind === 'push') {
this._pushEvt = false;
if (this._pushTimer) clearTimeout(this._pushTimer);
this._pushTimer = setTimeout(() => {
if (!this._pushEvt) this.trace('⚠️ [3s 无推流回调] ①基座是否重做 ②License/包名 ③URL 可达性');
}, 3000);
} else {
this._playEvt = false;
if (this._playTimer) clearTimeout(this._playTimer);
this._playTimer = setTimeout(() => {
if (!this._playEvt) this.trace('⚠️ [3s 无播放回调] ①基座是否重做 ②License/包名 ③URL 可达性');
}, 3000);
}
}
}
}
</script>
<style>
/* ================= 主题色板 ================= */
/* 背景 #0b0e14 · 卡片 #151a23 · 主色 #2f6bff · 成功 #22c55e · 警告 #f59e0b · 错误 #ef4444 */
.page {
flex: 1;
background-color: #0b0e14;
}
.container {
padding: 24rpx 28rpx 48rpx;
}
/* ---------- 顶部 ---------- */
.hero {
margin: 12rpx 0 28rpx;
}
.hero-title {
color: #ffffff;
font-size: 34rpx;
font-weight: bold;
letter-spacing: 1rpx;
}
.hero-sub {
color: #7c8698;
font-size: 21rpx;
margin-top: 8rpx;
line-height: 30rpx;
}
/* ---------- 卡片 ---------- */
.card {
background-color: #151a23;
border: 1rpx solid rgba(255, 255, 255, 0.07);
border-radius: 24rpx;
padding: 28rpx;
margin-bottom: 28rpx;
}
.card-head {
flex-direction: row;
justify-content: space-between;
align-items: center;
margin-bottom: 20rpx;
}
.card-title {
color: #ffffff;
font-size: 28rpx;
font-weight: bold;
}
.tag {
color: #5b6678;
font-size: 19rpx;
}
/* ---------- License 徽标 ---------- */
.lic-pill {
font-size: 19rpx;
padding: 6rpx 18rpx;
border-radius: 999rpx;
font-weight: bold;
}
.tone-ok { color: #4ade80; background-color: rgba(34, 197, 94, 0.14); }
.tone-warn { color: #fbbf24; background-color: rgba(245, 158, 11, 0.14); }
.tone-danger { color: #f87171; background-color: rgba(239, 68, 68, 0.14); }
.tone-mute { color: #9aa3b2; background-color: rgba(148, 163, 184, 0.12); }
/* ---------- 表单 ---------- */
.field-label {
color: #8b93a5;
font-size: 21rpx;
margin-bottom: 8rpx;
}
.ipt {
background-color: #0f141d;
border: 1rpx solid rgba(255, 255, 255, 0.08);
color: #e8eaee;
padding: 18rpx 22rpx;
border-radius: 14rpx;
font-size: 23rpx;
margin-bottom: 20rpx;
}
.ipt-inline {
flex: 1;
margin-bottom: 0;
margin-right: 16rpx;
}
/* ---------- 截图预览 ---------- */
.snap-box {
height: 360rpx;
background-color: #07090e;
border: 1rpx solid rgba(255, 255, 255, 0.08);
border-radius: 16rpx;
margin-top: 20rpx;
align-items: center;
justify-content: center;
}
.snap-img {
width: 100%;
height: 360rpx;
}
.snap-ph {
color: #4b5563;
font-size: 21rpx;
}
.cell-save {
width: 100%;
margin-top: 16rpx;
}
.hint {
color: #6b7486;
font-size: 19rpx;
line-height: 28rpx;
margin-top: 12rpx;
}
/* ---------- 按钮 ---------- */
.btn {
background-color: #232a36;
color: #dfe3ea;
font-size: 24rpx;
border-radius: 14rpx;
padding: 18rpx 0;
text-align: center;
}
.btn-accent { background-color: #2f6bff; color: #ffffff; font-weight: bold; }
.btn-violet { background-color: #7c5cff; color: #ffffff; font-weight: bold; }
/* 按钮行:每行一个 flex 容器 space-between */
.btn-row {
flex-direction: row;
justify-content: space-between;
margin-bottom: 16rpx;
}
/* 注意:nvue(weex) 不支持「.btn-row .btn」后代选择器,宽度必须用单类 cell / cell-half */
.cell { width: 200rpx; }
.cell-half { width: 300rpx; }
/* ---------- 画面舞台 ---------- */
.stage {
width: 100%;
height: 400rpx;
background-color: #000000;
border: 1rpx solid rgba(255, 255, 255, 0.08);
border-radius: 18rpx;
margin-bottom: 10rpx;
}
.net {
color: #34d399;
font-size: 19rpx;
margin-bottom: 16rpx;
}
/* ---------- 日志 ---------- */
.log-card {
padding-bottom: 24rpx;
}
.log-scroll {
height: 380rpx;
background-color: #07090e;
border-radius: 16rpx;
padding: 12rpx 18rpx;
}
.log-line {
flex-direction: row;
padding: 6rpx 0;
border-bottom-width: 0;
}
.log-time {
color: #4b5563;
font-size: 19rpx;
margin-right: 14rpx;
width: 150rpx;
flex-shrink: 0;
}
.log-msg {
color: #c3cad6;
font-size: 21rpx;
flex: 1;
line-height: 30rpx;
}
.log-line.err .log-msg { color: #f87171; }
.log-line.warn .log-msg { color: #fbbf24; }
.log-line.ok .log-msg { color: #4ade80; }
</style>
三、API 一览
setLicence(options)
注册腾讯云直播 License(全局,App 生命周期内调用一次即可)。
| 参数 | 类型 | 说明 |
|---|---|---|
| options.licenseUrl | string | License URL(腾讯云控制台获取) |
| options.licenseKey | string | License Key |
tencentcloud-pusher(推流组件)
| 方法 | 说明 |
|---|---|
startPush(url) |
开始推流:自动开前摄 + 麦克风 + 推流(RTMP URL) |
stopPush() |
停止推流并关闭相机 |
switchCamera() |
切换前后摄像头 |
turnOnFlash(open: boolean) |
闪光灯(后置摄像头时有效) |
setBeautyDepth({beauty, whitening, ruddy}) |
自然美颜,取值 0~9 |
muteAudio(mute: boolean) |
麦克风静音(画面继续) |
snapshot(): number |
截取本地推流画面(需已开始推流),图片走 @snapshot |
pauseVideo() / resumeVideo() |
暂停 / 恢复推流视频轨 |
tencentcloud-player(拉流组件)
属性(props)
| 属性 | 类型 | 默认 | 说明 |
|---|---|---|---|
minCache |
number | 0.3 | 最小缓存(秒),startPlay 前通过 setCacheParams 设置;默认 0.3 降低延迟(SDK 原生默认 1) |
maxCache |
number | 0.8 | 最大缓存(秒),默认 0.8(SDK 原生默认 5);弱网可调大以减少卡顿 |
用法:<tencentcloud-player ref="player" :minCache="0.3" :maxCache="0.8" />
方法
| 方法 | 说明 |
|---|---|
startPlay(url) |
开始拉流(FLV / RTMP / LEB 均可) |
stopPlay() |
停止播放并完整销毁实例(解绑 observer → 音量归零 → stopPlay → 置空),再次 startPlay 会重建 |
pause() / resume() |
暂停 / 恢复画面(等价 pauseVideo/resumeVideo) |
pauseAudio() / resumeAudio() |
暂停 / 恢复音频轨 |
pauseVideo() / resumeVideo() |
暂停 / 恢复视频轨 |
setRenderMode(0|1|2) |
0=铺满(Fill) 1=完整(Fit) 2=拉伸(ScaleFill) |
setMute(boolean) |
播放静音(音量 0/100) |
setPlayoutVolume(volume: number) |
播放音量 0-100 |
switchStream(url) |
直播流无缝切换(FLV / LEB) |
setRenderMirrorMode(enable: boolean) |
播放画面左右镜像 |
enableVolumeEvaluation(intervalMs) |
音量评估间隔(ms,建议 300;<=0 关闭),结果走 @volume |
enableReceiveSeiMessage(enable, payloadType) |
接收 SEI,payloadType 支持 5/242/243 |
showDebugView(isShow) |
显示/隐藏播放器调试浮层 |
isPlaying(): number |
1=播放中 0=已停止 |
snapshot(): number |
截取播放画面(需正在播放),图片走 @snapshot |
返回
number的方法同步返回 SDK 错误码(0 成功;-98表示组件未初始化;-5 License 无效等以 SDK 为准)。 截图/音量等异步结果通过下方事件返回,而不是方法回调。实例生命周期:播放器实例与 observer 绑定在组件实例上(不跨页面共用)。页面返回/组件销毁时(
NVUnloaded与unmounted均会触发)自动完整销毁,解决「退出页面后仍有声音、再进页面复用失效实例导致闪退」的问题。缓存默认值已调低以适配互动直播,弱网如需更稳可增大maxCache。
推流端 type:
| type | 说明 |
|---|---|
error |
出错。code 为 SDK 错误码(常见:-5 License无效/包名不匹配;-1314 相机权限被拒;-1317 麦克风权限被拒) |
warning |
警告(同上码值含义) |
pushStatus |
推流状态。status ∈ disconnected / connecting / connectSuccess / reconnecting |
播放端 type:
| type | 说明 |
|---|---|
error / warning |
错误 / 警告(code、msg) |
connected |
已连接服务器 |
videoLoading / videoPlaying |
视频加载中 / 开始渲染 |
audioPlaying |
音频开始播放 |
@snapshot(截图结果)
调用 snapshot() 且 SDK 返回 0 后触发,载荷字段:
| 字段 | 说明 |
|---|---|
code |
0=成功;-1=图片数据转换失败 |
base64 |
PNG 图片的 base64 字符串(不含 data:image/png;base64, 前缀) |
width / height |
图片宽高(Android 端提供) |
msg |
失败原因(仅失败时) |
页面示例:
onSnapshot(e) {
const base64 = e.get('base64') // 若拿到 {detail:…} 结构,先做 e.detail ?? e 归一化
if (base64) this.snapSrc = 'data:image/png;base64,' + base64
}
@volume(播放音量评估)
需先调用 enableVolumeEvaluation(300);载荷 volume 为 0-100 的当前音量值。
@netstatus(实时网络状态)
字段:fps、videoBitrate、audioBitrate、rtt、netSpeed、appCpu、systemCpu、width、height。
五、常见问题 FAQ
| 现象 | 原因 / 解决 |
|---|---|
error code=-5(License) |
License 与当前包名(Android applicationId / iOS Bundle ID)不匹配,或已过期。去控制台核对并换绑;调试基座的包名也必须匹配 |
| 乱填 License 也显示"已激活" | 正常现象:setLicence 只注册不校验;是否有效看 startPush/startPlay 的 -5 返回 |
-1314 / -1317(权限) |
相机/麦克风未授权。Android 用 plus.android.requestPermissions 请求(不要用 uni.authorize,App 端不支持);曾被拒绝需到系统设置手动开启 |
| 推流/播放"无任何回调" | ① 是否使用自定义基座(标准基座无插件)② License 无效会静默:SDK 校验失败只同步返回错误码、不回调——本插件已把该失败转成 error 事件,更新插件后必有返回 |
云打包报 error18 找不到名称 tencent |
本地 UTS 编译依赖 libs/ 下的 aar(本插件已内置精简版 Live aar),勿自行移除 |
云打包 Swift 报 String + Int |
UTS 跨端代码中禁止「字符串 + 数字」拼接,请用模板字符串 ${code} |
| 集成体积 | Android 为精简版 Live aar,iOS 内置 Professional framework(约 20MB);可在 app-android/config.json 的 abis 按需裁剪 ABI |
兼容与许可
- 插件内嵌腾讯云 LiteAVSDK(Android LiteAVSDK_Live / iOS TXLiteAVSDK_Professional),其能力与合规要求遵循腾讯云移动直播官方条款
- 使用前请在腾讯云开通/绑定 License,正式商用需购买相应套餐
- 支持 uni-app(Vue2/Vue3 编译器均可,nvue 页面);如需 uni-app x(uvue)支持请联系作者适配

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