Feedback

直播场景

本教程主要介绍如何使用场景直播实现直播。

TRTC场景和角色

一般业务场景中,并不是所有用户都需要发布流,部分用户只需要订阅流。

TRTC 中有两种场景:
rtc 场景:默认场景。 rtc 场景中所有用户均为主播,该场景中不存在观众角色。
live 场景:该场景中的用户可以分为 主播 和 观众 两种角色。这两个角色的区别在于:
主播 可以推流。一个房间最多支持50个主播同时推流。
观众无法推流。观众数量没有限制。

主播端

主播侧实现音视频通话的流程与 rtc 场景的实现流程基本相同。参见:基础音视频通话。

主要区别在于调用 trtc.enterRoom() 时设置的参数场景和角色。参见如下示例代码:
await trtc.enterRoom({
scene: TRTC.TYPE.SCENE_LIVE,
role: TRTC.TYPE.ROLE_ANCHOR,
sdkAppId,
userId,
userSig,
roomId
});

观众端

作为观众进入房间

将角色参数设置为TRTC.TYPE.ROLE_AUDIENCE。
await trtc.enterRoom({
scene: TRTC.TYPE.SCENE_LIVE,
role: TRTC.TYPE.ROLE_AUDIENCE,
sdkAppId,
userId,
userSig,
roomId
});

播放远程音频

默认情况下,SDK会自动播放远程音频,您无需调用任何API即可播放远程音频。
自动播放策略限制
如果用户在进入房间之前没有与页面进行交互,则由于 自动播放策略限制,音频自动播放可能会失败。需要参见 自动播放限制处理 进行处理。
如果您不希望 SDK 自动播放音频,可以尝试以下方法:
trtc.on(TRTC.EVENT.REMOTE_AUDIO_AVAILABLE, event => {
// Call this api when you need to play remote audio.
trtc.muteRemoteAudio(event.userId, false);
// Stop remote audio
trtc.muteRemoteAudio(event.userId, true);
})
// Setting autoReceiveAudio = false to turn off automatic audio playback.
await trtc.enterRoom({ ..., autoReceiveAudio: false });

播放远程视频

1. 进入房间前监听 TRTC.EVENT.REMOTE_VIDEO_AVAILABLE 事件,以接收所有远程用户视频发布事件。
2. 收到该事件后,调用 trtc.startRemoteVideo() 播放远端视频流。
trtc.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, ({ userId, streamType }) => {
// To play the video image, you need to place an HTMLElement in the DOM,
// which can be a div tag, assuming its id is `${userId}_${streamType}`
const view = `${userId}_${streamType}`;
trtc.startRemoteVideo({ userId, streamType, view });
});

如何切换角色

观众角色没有推流权限,因此如果观众想要与主播通话,需要通过 trtc.switchRole 切换到主播角色,然后再推流。
// Switch to the anchor
await trtc.switchRole(TRTC.TYPE.ROLE_ANCHOR);

// Turn on mic and camera, then the other anchor in the room will able to receive your audio and video.
await trtc.startLocalAudio();
await trtc.startLocalVideo();

// Switch back to the audience when the calling is ended
await trtc.switchRole(TRTC.TYPE.ROLE_AUDIENCE);