欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

实现音频和视频通话的 Android 单应用程序 - 4. 代码

最编程 2024-04-13 15:53:02
...

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,不能重复。

推荐阅读