加入多频道
- Android
更新时间不可用
了解实时互动 RTC 在不同平台上的加入多频道方式,包括接入流程、关键配置和平台差异。
声网 SDK 支持用户同时加入多个频道,同一时间可以在多个频道中接收和发布音视频流。
技术原理
SDK 通过 RtcConnection 对象和 RtcEngineEx 类实现多频道功能。RtcEngineEx 提供适用于指定 RtcConnection 对象的方法。
RtcConnection 对象包含用于识别连接的如下信息:
- 频道名称
- 本地用户的用户 ID
你可以创建多个 RtcConnection 对象,并为每个对象设置不同的频道名称和用户 ID。
如果要加入多个频道,多次调用 RtcEngineEx 类中的 joinChannelEx 并设置不同的 RtcConnection 对象。加入多频道时请注意:
- 每个
RtcConnection对象的用户 ID 是唯一的,且不为0。 - 可以为
joinChannelEx中的RtcConnection对象配置发布和订阅选项。 - 每个
RtcConnection可以独立发布多路音频流和一路视频流。 - 不同频道的事件通过你在调用
joinChannelEx方法时,向eventHandler所传入的不同IRtcEngineEventHandler对象来回调。
前提条件
在进行操作之前,请确保你已经在项目中实现了基本的实时音视频功能。详见实现音视频互动。
实现方法
为实现多频道功能,你需要对每个频道进行如下设置:
-
在项目的
/app/java/com.example.<projectname>/MainActivity文件中定义RtcConnection对象。Java private RtcConnection rtcConnection2 = new RtcConnection(); -
使用随机的用户 ID 加入频道。
Java private boolean joinSecondChannel() { ChannelMediaOptions option = new ChannelMediaOptions(); mediaOptions.autoSubscribeAudio = true; mediaOptions.autoSubscribeVideo = true; rtcConnection2.channelId = channel2; rtcConnection2.localUid = new Random().nextInt(512)+512; int ret = engine.joinChannelEx("your token",rtcConnection2,mediaOptions,iRtcEngineEventHandler2); return (ret == 0); } -
监听
rtcConnection2中的事件,并在onUserJoined回调中设置远端视频。Java private final IRtcEngineEventHandler iRtcEngineEventHandler2 = new IRtcEngineEventHandler() { @Override public void onJoinChannelSuccess(String channel, int uid, int elapsed) { Log.i(TAG, String.format("channel2 onJoinChannelSuccess channel %s uid %d", channel2, uid)); showLongToast(String.format("onJoinChannelSuccess channel %s uid %d", channel2, uid)); } @Override public void onUserJoined(int uid, int elapsed) { Log.i(TAG, "channel2 onUserJoined->" + uid); showLongToast(String.format("user %d joined!", uid)); Context context = getContext(); if (context == null) { return; } handler.post(() -> { // 显示远端视频流 SurfaceView surfaceView = null; if (fl_remote2.getChildCount() > 0) { fl_remote2.removeAllViews(); } // 通过 RtcEngine 创建渲染视图 surfaceView = new SurfaceView(context); surfaceView.setZOrderMediaOverlay(true); // 将视图加入远端容器 fl_remote2.addView(surfaceView, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); // 设置远端视图 engine.setupRemoteVideoEx(new VideoCanvas(surfaceView, RENDER_MODE_FIT, uid), rtcConnection2); }); } };
参考信息
API 参考
示例项目
声网提供了开源的示例项目供你参考,你可以前往下载或查看其中的源代码。