class ViewController: UIViewController, ByteRTCEngineDelegate, ByteRTCRoomDelegate {
var rtcEngine: ByteRTCEngine?
var rtcRoom: ByteRTCRoom?
override func viewDidLoad() {
self.bindLocalRenderView()
ByteRTCEngine.destroyRTCEngine()
joinButton.isSelected = !joinButton.isSelected
if joinButton.isSelected {
joinButton.setTitle("离开房间", for: .normal)
self.rtcRoom = self.rtcEngine?.createRTCRoom(roomId)
self.rtcRoom?.delegate = self
let userInfo = ByteRTCUserInfo.init()
userInfo.userId = userId
let roomCfg = ByteRTCRoomConfig.init()
roomCfg.isPublishAudio = true
roomCfg.isPublishVideo = true
roomCfg.isAutoSubscribeAudio = true
roomCfg.isAutoSubscribeVideo = true
self.rtcRoom?.joinRoom(token, userInfo: userInfo, userVisibility: true, roomConfig: roomCfg)
joinButton.setTitle("加入房间", for: .normal)
let engineCfg = ByteRTCEngineConfig.init()
engineCfg.appID = kAppID
engineCfg.parameters = [:]
self.rtcEngine = ByteRTCEngine.createRTCEngine(engineCfg, delegate: self)
self.rtcEngine?.startVideoCapture()
self.rtcEngine?.startAudioCapture()
func bindLocalRenderView() {
let canvas = ByteRTCVideoCanvas.init()
canvas.view = self.localView
canvas.renderMode = .hidden
self.rtcEngine?.setLocalVideoCanvas(withCanvas: canvas);
func bindRemoteRenderView(streamId: String) {
let canvas = ByteRTCVideoCanvas.init()
canvas.view = remoteView
canvas.renderMode = .hidden
self.rtcEngine?.setRemoteVideoCanvas(streamId, withCanvas: canvas)
func removeRemoteRenderView(streamId: String) {
let canvas = ByteRTCVideoCanvas.init()
canvas.renderMode = .hidden
self.rtcEngine?.setRemoteVideoCanvas(streamId, withCanvas: canvas)
func createUI() -> Void {
let width = self.view.bounds.size.width*0.5
let height = self.view.bounds.size.height*0.5
localView.frame = CGRect(x: 0, y: 0, width: width, height: height)
self.view.addSubview(localView)
remoteView.frame = CGRect(x: width, y: 0, width: width, height: height)
self.view.addSubview(remoteView)
joinButton.frame = CGRect(x: 10, y: height + 30, width: width*2 - 20, height: 44)
self.view.addSubview(joinButton)
lazy var joinButton: UIButton = {
let button = UIButton(type: .custom)
button.backgroundColor = .blue
button.setTitle("加入房间", for: .normal)
button.addTarget(self, action: #selector(joinRoom), for: .touchUpInside)
lazy var remoteView: UIView = {
let view = UIView.init()
view.backgroundColor = .lightGray
lazy var localView: UIView = {
let view = UIView.init()
view.backgroundColor = .lightGray
func rtcRoom(_ rtcRoom: ByteRTCRoom, onRoomStateChanged roomId: String, withUid uid: String, state: Int, extraInfo: String) {
print("Join Room Success")
func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamVideo streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) {
DispatchQueue.main.async {
self.bindRemoteRenderView(streamId: streamId)
DispatchQueue.main.async {
self.removeRemoteRenderView(streamId: streamId)
func rtcRoom(_ rtcRoom: ByteRTCRoom, onUserPublishStreamAudio streamId: String, info: ByteRTCStreamInfo, isPublish: Bool) {