加入多频道

  • macOS

更新时间

了解实时互动 RTC 在不同平台上的加入多频道方式,包括接入流程、关键配置和平台差异。

声网 SDK 支持用户同时加入多个频道,同一时间可以在多个频道中接收和发布音视频流。

技术原理

SDK 提供 AgoraRtcConnection 对象和 AgoraRtcEngineKit(Ex) 类实现多频道功能。AgoraRtcEngineKit(Ex) 提供适用于指定 AgoraRtcConnection 对象的方法。

AgoraRtcConnection 对象包含用于识别连接的如下信息:

  • 频道名称
  • 本地用户的用户 ID

你可以创建多个 AgoraRtcConnection 对象,并为每个对象设置不同的频道名称和用户 ID。

如果要加入多个频道,多次调用 AgoraRtcEngineKit(Ex) 类中的 joinChannelExByToken[1/2] 并设置不同的 AgoraRtcConnection 对象。加入多频道时请注意:

  • 每个 AgoraRtcConnection 对象的用户 ID 是唯一的,且不为 0。
  • 可以为 joinChannelExByToken[1/2] 中的 AgoraRtcConnection 对象配置发布和订阅选项。
  • 每个 AgoraRtcConnection 可以独立发布多路音频流和一路视频流。
  • 不同频道的事件通过你在调用 joinChannelExByToken 方法时,向 delegate 所传入的不同 AgoraRtcEngineDelegate 对象来回调。

前提条件

在进行操作之前,请确保你已经在项目中实现了基本的实时音视频功能。详见实现音视频互动。

实现方法

为实现多频道功能,你需要对每个频道进行如下设置:

  1. 在项目的 ViewController.swift 文件中定义 AgoraRtcConnection 对象。

    Swift
    let connection1 = AgoraRtcConnection()
  2. 使用随机的用户 ID 加入频道。

    Swift
    var mediaOptions = AgoraRtcChannelMediaOptions()
    mediaOptions.autoSubscribeVideo = .of(true)
    mediaOptions.autoSubscribeAudio = .of(true)
    connection1.channelId = channelName1
    connection1.localUid = UInt.random(in: 1001...2000)
    var result = agoraKit.joinChannelEx(byToken: "your token", connection: connection1, delegate: channel1, mediaOptions: mediaOptions, joinSuccess: nil)
    channel1.channelId = channelName1
    channel1.connecitonDelegate = self
    if result != 0 {
        self.showAlert(title: "Error", message: "joinChannel1 call failed: \(result), please check your params")
    }
  3. 在 didJoinedOfUid 回调中设置远端视频。

    Swift
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        guard let channelId = channelId, let channel2RemoteVideo = view else {
            return
        }
        LogUtils.log(message: "remote user join room channel \(channelId): \(uid) \(elapsed)ms", level: .info)
    
        // 在该操作中,仅一个远端视频视图可用
        // 此处,我们检查是否存在标签为该 uid 的视图
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        // 待绑定的视图
        videoCanvas.view = channel2RemoteVideo.videoView
        videoCanvas.renderMode = .hidden
        let connection = AgoraRtcConnection()
        connection.channelId = channelId
        connection.localUid = CONNECTION_2_UID
        engine.setupRemoteVideoEx(videoCanvas, connection: connection)
        remoteUid = uid
    }

参考信息

API 参考

示例项目

声网在 GitHub 上提供如下开源的示例项目。你可以前往下载,或查看其中的源代码: