基于TRTC和IM實作web群直播
本文主要通過介紹網頁版群直播基礎功能和實作流程來告訴大家TWebLive 能用來做什么,如何把TWebLive集成到專案中 ,
WEB群直播和微信群直播功能類似,不需要下載專業的直播APP就可以直播,在網頁即時通信工具中集成群直播功能后,群組內的任何成員都可以發起直播,多個成員可以同時發起直播,其他成員通過群組內開播訊息進入自己喜歡的直播間,直播間內不僅可以發送普通文本訊息、還可以通過自定義訊息實作彈幕、禮物、抽獎等多種互動訊息, 針對這樣一款群直播產品功能,可以通過集成騰訊會議產品部通信終端研發中心WEB組研發的WEB直播互動SDK—TWebLive [1]來實作,
一、網頁版群直播效果


二、網頁版群直播實作框架

三、網頁版群直播基礎功能介紹
3.1、在騰訊云即時通信IM Demo[2]中可以通過2種方式體驗群直播功能,
(1)、通過全域群直播入口進入,此時不會向任何群組發送群直播開播/停播訊息通知,

(2)、在Demo中創建Public、Work、Meeting任意一個群組型別(不支持在AVChatRoom中開啟群直播),打開會話視窗,點擊群直播按鈕開啟群直播,

3.2、進入群直播界面后可以輸入直播名稱,底部操作區設定有開始直播/結束直播,攝像頭和麥克風開關按鈕,

3.3、開播時會給群組內所有成員推送開播通知,群組成員可以通過點擊訊息卡片進入直播間觀看直播,

3.4、直播程序中主播端可以查看主播個人資訊、直播在人數、直播時長,主播可以發送普通文本訊息進行互動,

3.5、觀眾進入直播間可發送普通文本和禮物訊息,暫停觀看不影響與主播進行訊息互動,

3.6、主播結束直播時會給群組內推送結束直播通知,直播結束后再點擊卡片會提示直播已結束,不能再進入直播間,

3.7、網頁版群直播與云通信IM APP群直播互通體驗


四、實作群直播的核心技術—TWebLive
網頁版群直播功能的實作依賴TWebLive SDK,TWebLive集成了騰訊云實時音視頻TRTC[3]、騰訊云即時通信IM[4]、騰訊云超級播放器TcPlayer[5],覆寫了Web直播互動場景常見的功能,封裝了簡單易用的API[6],
TWebLive主要提供了三大核心功能:主播端推流,觀眾端觀看,直播互動,主播端推流基于實時音視頻TRTC實作,觀眾端CDN觀看基于TcPlayer實作,直播互動基于即時通信IM實作,
五、如何利用TWebLive實作群直播功能
5.1、接入TWebLive
在TRTC應用或者IM應用中均可接入TWebLive,這里主要介紹在IM應用中接入TWeblive的流程,接入前,需要在騰訊云即時通信IM控制臺創建的IM應用中開通騰訊云實時音視頻服務,開通音視頻服務后,還需要在騰訊云直播控制臺配置直播域名且域名需要配置HTTPs,

在專案中通過npm安裝最新版本的tim-js-sdk、trtc-js-sdk、tweblive,如果專案已經集成有tim-js-sdk或trtc-js-sdk,直接將其升級到最新版本即可,
npm install im-js-sdk --save
npm install trtc-js-sdk --save
npm install tweblive --save
在專案中引入tweblive
import TWebLive from 'tweblive'
Vue.prototype.TWebLive = TWebLive
如果需要通過script標簽外鏈的方式引入,需要將tim-js.js、trtc.js、tweblive.js拷貝至專案中,按順序引入,
<script src="./trtc.js"></script>
<script src="./tim-js.js"></script>
<script src="./tweblive.js"></script>
5.2、群直播主播端主要功能實作如下
// 初始化pusher
init() {
this.pusher = this.TWebLive.createPusher({
userID: this.user.userID
})
this.setRenderView()
this.pusher.on(this.TWebLive.EVENT.RTC_CONNECTION_STATE_CHANGED, this.onRTCConnectionStateChanged) this.pusher.on(this.TWebLive.EVENT.RTC_CLIENT_BANNED,this.onRTCClientBanned)
this.pusher.on(this.TWebLive.EVENT.RTC_CLIENT_ERROR,this.onRTCError)
},
// eslint-disable-next-line no-unused-vars
onRTCConnectionStateChanged(event) {},
// eslint-disable-next-line no-unused-vars
onRTCClientBanned(event) {},
// eslint-disable-next-line no-unused-vars
onRTCError(event) {},
//開啟本地預覽
setRenderView() {
this.pusher.setRenderView({
elementID: 'video-container',
audio: true,
video: true
}).then(() => {
// 設定背景
let el =document.getElementById('videocontainer').childNodes
el[0].style.backgroundColor = 'rgba(0,0,0,0)'
this.isStartCamera = false
}).catch(() => {})
},
// 打開攝像頭
startCamera() {
this.pusher.startCamera().then(() => {
this.isStartCamera = false
}).catch(() => {})
},
// 關閉攝像頭
stopCamera() {
this.pusher.stopCamera().then(() => {
this.isStartCamera = true
}).catch(() => {})
},
// 打開麥克風
startMicrophone() {
this.pusher.startMicrophone().then(() => {
this.isMute = false
}).catch(() => {})
},
// 關閉麥克風
stopMicrophone() {
this.pusher.stopMicrophone().then(() => {
this.isMute = true
}).catch(() => {})
},
// 通過業務服務器創建直播房間
async createRoom() {},
//開始推流
async startPushStream() {
await this.createRoom()
// streamID生成規則:sdkappid_roomid_userid_main
const streamID = `${this.user.sdkAppID}_${this.roomID}_${this.user.userID}_main`
// 對userSig進行encode,防止userSig中帶有+時被瀏覽器決議為空格,導致trtc ws連接失敗
const url = `room://livedomainname=xxx.xxx.com&sdkappid=${this.user.sdkAppID}&roomid=${this.roomID}&userid=${this.user.userID}&usersig=${encodeURIComponent
(this.user.userSig)}&streamid=${streamID}`
this.pusher.startPush(url).then(() => {
// 發送開播群通知
this.sendNoticeToGroup(1)
}).catch(() => {})
},
// 停止推流
async stopPush() {
await this.pusher.stopPush()
// 發送直播結束群通知
this.sendNoticeToGroup(0)
},
// 給群內發送開始直播、結束直播自定義訊息
// roomStatus 1 開始直播 0 結束直播
sendNoticeToGroup(roomStatus) {
if (!this.groupLiveInfo.groupID) { return }
const { userID, nick, avatar } = this.user.currentUserProfile
// 自定義訊息結構體,根據實際需要修改,以下結構體僅為Demo使用
const form = {
roomId: this.roomID,
roomName: this.roomName,
roomCover: avatar,
roomStatus: `${roomStatus}`,
anchorName: nick,
version: 4,
roomType: 'liveRoom',
anchorId: userID,
businessID: 'group_live'
}
const message = this.tim.createCustomMessage({
to: this.groupLiveInfo.groupID,
conversationType: this.TIM.TYPES.CONV_GROUP,
priority: this.TIM.TYPES.MSG_PRIORITY_NORMAL,
payload: {
data: JSON.stringify(form),
description: '',
extension: '',
},
})
this.tim.sendMessage(message).then(() => {}).catch(() => {})
}
5.3、群直播觀眾端主要功能實作如下
// 初始化player
init() {
this.player = this.TWebLive.createPlayer()
this.player.setCustomConfig({
autoplay: true,
poster: { style:'cover', src: poster },
pausePosterEnabled: false,
wording: {
1:'您觀看的直播已結束哦~ ',
2:'您觀看的直播已結束哦~ ',
4:'您觀看的直播已結束哦~ ',
13:'您觀看的直播已結束',
2032: '請求視頻失敗,請檢查網路',
2048: '請求m3u8檔案失敗,可能是網路錯誤或者跨域問題'
}
})
// 監聽播放事件
this.player.on(this.TWebLive.EVENT.PLAYER_PLAYING,this.onPlayerPlaying)
// 監聽暫停事件
this.player.on(this.TWebLive.EVENT.PLAYER_PAUSE,this.onPlayerPause)
// 監聽瀏覽器不允許自動播放事件
this.player.on(this.TWebLive.EVENT.PLAYER_AUTOPLAY_NOT_ALLOWED, this.onPlayerAutoPlayNotAllowed)
// 監聽播放例外事件
this.player.on(this.TWebLive.EVENT.PLAYER_ERROR,this.onPlayerError)
this.setRenderView()
},
// eslint-disable-next-line no-unused-vars
onPlayerPlaying(event) {},
// eslint-disable-next-line no-unused-vars
onPlayerPause(event) {},
// eslint-disable-next-line no-unused-vars
onPlayerAutoPlayNotAllowed(event) {
this.$store.commit('showMessage', {
message: '不能自動播放',
type: 'info'
})
},
//開始播放
startPlay() {
const streamID = `${this.user.sdkAppID}_${this.roomID}_${this.anchorId}_main`
const flv = `https://xxx.xx.com/live/${streamID}.flv`
const hls = `https://xxx.xx.com/live/${streamID}.m3u8`
const url = `https://flv=${encodeURIComponent(flv)}&hls=${encodeURIComponent(hls)}`
this.player.startPlay(url).then(() => {
this.isPlaying = true
}).catch(() => {})
},
//暫停播放
pauseVideo() {
this.player.pauseVideo().then(() => {
this.isPlaying = false
}).catch(() => {})
},
// 恢復播放
resumeVideo() {
this.player.resumeVideo().then(() => {
this.isPlaying = true
}).catch(() => {})
},
// 調節播放器音量
setPlayoutVolume() {
this.player.setPlayoutVolume(this.volumeValue)
},
// 停止播放
stopPlay() {
this.player.stopPlay()
this.isPlaying = false
}
5.4、群直播互動功能實作
由于騰訊云即時通信IM Demo[2]中已經集成了IM應用,直播互動部分的功能通過IM SDK API實作,
// 創建直播互動群
async createGroupLiveAvChatRoom() {
await this.tim.createGroup({
name: this.roomName,
groupID: this.roomID,
type: this.TIM.TYPES.GRP_AVCHATROOM,
})
},
// 進入直播互動群
joinGroupLiveAvChatRoom() {
this.tim.joinGroup({
groupID: this.groupLiveInfo.roomID
}).then((imResponse) => {
const status = imResponse.data.status
if (status === this.TIM.TYPES.JOIN_STATUS_SUCCESS || status === this.TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP) {
// 加群成功后才可以發訊息
this.sendAvailable = true
}
}).catch(() => {})
},
// 發送普通文本訊息
sendTextMessge() {
const message = this.tim.createTextMessage({
to: this.groupLiveInfo.roomID,
conversationType: this.TIM.TYPES.CONV_GROUP,
payload: { text: this.messageContent }
})
this.tim.sendMessage(message).catch(error => {})
this.messageContent = ''
}
// 發送禮物訊息
sendGiftMessage() {
// data為禮物訊息結構體,根據實際需要自己定義
const data = {}
const message = this.tim.createCustomMessage({
to: this.groupLiveInfo.roomID,
conversationType: this.TIM.TYPES.CONV_GROUP,
payload: {
data: JSON.stringify(data),
description: '',
extension: ''
}
})
this.tim.sendMessage(message).catch(error => {})
}
代碼片段是在Vue框架下實作,代碼中使用到的變數維護在Vuex 和組件data屬性中,可以復制以上代碼片段到Vue專案中,即可快速搭建一個網頁版群直播功能,
六、TWebLive SDK體積優化
TWebLive SDK 1.0.0打包時將IM SDK、TRTC SDK、TcPlayer 集成輸出,導致輸出的包體積很大(接近1M),如果在已有IM或者TRTC應用中接入TWebLive時,存在重復參考的問題,為了提升接入體驗,已發布TWebLive 1.1.0版本,主要是在1.0.0的基礎上優化SDK的打包方式,把IM SDK和TRTC SDK作為外部依賴打包,SDK體積減少了78%,接入TWeblive時手動安裝IM SDK和TRTC SDK即可,
七、注意事項
第一、接入TWebLive時,需要安裝最新版本的tim-js-sdk、trtc-js-sdk,避免引起版本兼容性問題,
第二、Pusher和Player中使用到的SDKAppID必須與IM應用的SDKAppID保持一致,
第三、由于 H.264 著作權限制,華為系統的 Chrome 瀏覽器和以 Chrome WebView 為內核的瀏覽器均不支持 TRTC 桌面瀏覽器端 SDK 的正常運行,
參考資料:
[1] TWebLive詳情
[2] 騰訊云即時通信IM在線 Demo
[3] 騰訊云實時音視頻 TRTC
[4] 騰訊云即時通信IM
[5] 騰訊云超級播放器 TCPlayer
[6] TWebLive介面手冊
[7] 騰訊云即時通信介面手冊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/230367.html
標籤:其他
上一篇:RTMP推流協議視頻直播點播平臺/人臉識別系統EasyDSS 定制標簽檢索功能檢索資料出錯的問題排查
下一篇:vs2017安裝詳情
