前言
上一篇講解了怎麼實現Android uni-app封裝原生插件,這篇講解一下,把anyRTC的RTC(音視頻通訊)封裝uni-app 實現音視頻通話。
不瞭解anyRTC的小夥伴,可以點擊下面鏈接:
1.效果圖
先上圖,後講解!
1.1 首頁
1.2 遊客界面
1.3 主播界面
2.GitHub地址
uni-app demo: 點擊下載
3.demo下載:
下載地址:點擊下載
掃碼下載:
4.代碼
4.1 集成插件
const RtcModule = uni.requireNativePlugin('AR-RtcModule');
- AR-RtcModule:插件名稱,首頁集成插件
4.2 初始事件回調
//callback 接收
callbackFn() {
RtcModule.setCallBack((res) => {
switch (res.engineEvent) {
case "onWarning":
this.promptFn("warn", res.warningCode);
break;
case "onError":
res.errorCode != 18 ? this.promptFn("error", res.errorCode) : '';
break;
case "onJoinChannelSuccess": //用戶加入成功
uni.hideLoading();
this.role == 1 ? this.PeerVideoUser.push(res.uid) : "";
this.videoShow = true;
setTimeout(() => {
// this.videoShowBg = false;
this.promptText = ""
//揚聲器
RtcModule.setEnableSpeakerphone({
"enabled": true
}, (res) => {
})
setTimeout(() => {
// 啓用視頻模塊。
this.role == 1 ? this.setupLocalVideoFn() : RtcModule.enableVideo((res) => {
});
}, 200)
}, 2000)
break;
case "onLeaveChannel": //離開頻道回調
setTimeout(() => {
this.closeAll()
}, 500)
break;
case "onUserJoined": //遠端用戶加入當前頻道回調。
// this.promptFn("info", "遠端用戶加入當前頻道回調");
this.PeerVideoUser.push(res.uid);
break;
case "onUserOffline": //遠端用戶離開當前頻道回調。
this.PeerVideoUser = this.PeerVideoUser.filter((x) => x !== res.uid);
break;
case "onFirstLocalAudioFrame": //已發送本地音頻首幀的回調。(頁面上添加音頻)
break;
case "onFirstLocalVideoFrame": //已顯示本地視頻首幀的回調。(頁面添加本地視頻)
// this.promptFn("error", "已顯示本地視頻首幀的回調");
break;
case "onFirstRemoteVideoDecoded": //已完成遠端視頻首幀解碼回調。(頁面添加遠端視頻)
// this.promptFn("info", "已完成遠端視頻首幀解碼回調");
this.promptText = "請稍等。。。"
let uid = []
uid.push(res.uid)
setTimeout(() => {
this.promptText = "";
// this.videoShowBg = false; //設置背景開關
setTimeout(() => {
uid.map(item => {
this.$refs[`popup${
item}`][0].setupRemoteVideo({
"renderMode": 1,
"channelId": this.chanel,
"uid": item,
"mirrorMode": 0
}, (res) => {
})
//預覽
RtcModule.startPreview((res) => {
});
})
}, 500)
}, 2000)
break;
}
})
},
- res.engineEvent:接收各種回調,加入頻道成功,離開頻道,錯誤碼等。
4.3 創建實例
await RtcModule.create({
"appId": this.appid //anyRTC 爲 App 開發者簽發的 App ID。每個項目都應該有一個獨一無二的 App ID。如果你的開發包裏沒有 App ID,請從anyRTC官網(https://www.anyrtc.io)申請一個新的 App ID
}, (res) => {
});
4.4 設置角色
setClientRole(num) {
this.role = num;
//設置直播場景下的用戶角色
RtcModule.setClientRole({
"role": Number(num) //1:爲主播,2:遊客
}, (ret) => {
});
},
4.5 加入頻道
await RtcModule.joinChannel({
"token": "",
"channelId": this.channel,
"uid": this.uid
}, (res) => {
})
- token: 註冊不開啓token驗證,可以爲空着。
- channelId: 你需要加入的頻道ID。
- uid: 每個用戶分配唯一UID,不能重複。
4.6 離開銷燬
RtcModule.leaveChannel((res) => {
}); //離開頻道
RtcModule.destroyRtc((res) => {
}); //銷燬頻道
5.總結
基本重要的接口,在這裏就基本上介紹完啦,如果大家還有什麼疑問,可以在評論區留言!
作者:anyRTC-東慕雨