在UniApp中实现直播推流与拉流需结合原生能力和跨平台特性,主要分为以下步骤:
一、推流实现方案
- 微信小程序端
使用<live-pusher>
组件:
<live-pusher
url="rtmp://push.example.com/live/streamkey"
mode="SD"
class="pusher"
@statechange="onPushStateChange"
/>
需在manifest.json
配置权限:
"mp-weixin": {
"usingComponents": true,
"permission": {
"scope.record": {"desc": "需要麦克风权限"},
"scope.camera": {"desc": "需要摄像头权限"}
}
}
- App端(Android/iOS)
需通过原生插件实现:
- 集成第三方SDK(如阿里云推流SDK)
- 使用uni原生插件封装:
const pushModule = uni.requireNativePlugin('AliyunLivePusher')
pushModule.startPush({
url: 'rtmp://push.example.com/live/streamkey',
videoQuality: 2 // 清晰度等级
})
二、拉流实现方案
- 基础播放器
使用<live-player>
组件:
<live-player
src="rtmp://play.example.com/live/streamkey"
mode="RTC"
autoplay
@fullscreenchange="onFullscreenChange"
/>
- 高级功能扩展
通过WebView集成H5播放器:
// 在vue页面中
<web-view src="https://player.example.com?stream=streamkey"></web-view>
三、关键配置项
推流参数:{分辨率≥720×1280码率∈[1500,3000]kbps帧率≥25fps拉流延时:缓存时间网络带宽+解码时间≤2s \begin{aligned} \text{推流参数} &: \left\{ \begin{array}{l} \text{分辨率} \geq 720 \times 1280 \\ \text{码率} \in [1500, 3000] \text{kbps} \\ \text{帧率} \geq 25 \text{fps} \end{array} \right. \\ \text{拉流延时} &: \frac{\text{缓存时间}}{\text{网络带宽}} + \text{解码时间} \leq 2s \end{aligned} 推流参数拉流延时:⎩⎨⎧分辨率≥720×1280码率∈[1500,3000]kbps帧率≥25fps:网络带宽缓存时间+解码时间≤2s
四、注意事项
- 跨平台兼容
通过条件编译处理差异:
// #ifdef MP-WEIXIN
wx.requestSubscribeMessage() // 申请订阅权限
// #endif
// #ifdef APP-PLUS
plus.android.requestPermissions(['CAMERA','RECORD_AUDIO'])
// #endif
- 性能优化
- 开启硬件加速编码
- 动态调整码率:
function adjustBitrate(networkType) {
const bitrateMap = {
'wifi': 3000,
'4g': 2000,
'3g': 1500
}
return bitrateMap[networkType] || 1000
}
五、完整示例
<template>
<view>
<!-- 推流端 -->
<live-pusher v-if="isAnchor" :url="pushUrl" @error="onPushError" />
<!-- 播放端 -->
<live-player v-else :src="playUrl" @statechange="onPlayStateChange" />
<!-- 控制栏 -->
<view class="control-bar">
<button @click="toggleCamera">切换摄像头</button>
<button @click="toggleMute">{{ isMuted ? '取消静音' : '静音' }}</button>
</view>
</view>
</template>
<script>
export default {
data() {
return {
isAnchor: true,
pushUrl: 'rtmp://your_push_server',
playUrl: 'rtmp://your_play_server',
isMuted: false
}
},
methods: {
toggleCamera() {
const ctx = uni.createLivePusherContext()
ctx.switchCamera()
},
toggleMute() {
this.isMuted = !this.isMuted
const ctx = uni.createLivePlayerContext()
ctx.mute(this.isMuted)
}
}
}
</script>
调试建议:
- 使用
uni.getNetworkType()
监测网络状态 - 通过
uni.createLivePusherContext()
获取推流状态 - 使用Chrome开发者工具模拟不同网络环境
扩展方向:
- 集成IM系统实现弹幕互动
- 添加美颜滤镜处理(需原生插件)
- 实现直播录制回放功能
实际部署时需注意:
服务端成本=峰值带宽(Mbps)×单价(元/Mbps/天)×301.024
\text{服务端成本} = \frac{\text{峰值带宽(Mbps)} \times \text{单价(元/Mbps/天)} \times 30}{1.024}
服务端成本=1.024峰值带宽(Mbps)×单价(元/Mbps/天)×30