集成
本教程主要介绍如何实现一个基本的音视频通话。
安装
npm install trtc-sdk-v5 --save
yarn add trtc-sdk-v5
或者手动下载:
1. 下载 trtc.js。
2. 将 trtc.js 复制到您的项目中。
用法
导入 TRTC SDK
import TRTC from 'trtc-sdk-v5';
如果您手动下载trtc.js,则需要使用script标签导入TRTC SDK。
<script src="/your_path/trtc.js"></script>
创建TRTC对象
const trtc = TRTC.create();
进入房间
try {await trtc.enterRoom({ sdkAppId, userId, userSig, roomId: 8888 });console.log('enter room successfully');} catch (error) {console.error('failed to enter room ' + error);}
打开/关闭麦克风
await trtc.startLocalAudio();
await trtc.stopLocalAudio();
打开/关闭摄像头
// To preview the camera image, you need to place an HTMLElement in the DOM,// which can be a div tag, assuming its id is local-video.const view = 'local-video';await trtc.startLocalVideo({ view });
await trtc.stopLocalVideo();
播放远程音频
默认情况下,SDK会自动播放远程音频,因此您无需调用任何API来手动播放。
以下代码片段展示了当您不希望自动播放音频时如何调用 API 来播放远程音频。
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 audiotrtc.muteRemoteAudio(event.userId, true);})// SettingautoReceiveAudio = 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 });});
退出房间
await trtc.exitRoom();// After the exit is successful, you can call the trtc.destroy method to// destroy the instance and release related resources in a timely manner// if you do not need to use the trtc instance later.// The destroyed trtc instance cannot be used again and a new instance needs to be created.trtc.destroy();
处理被踢
除了主动退出房间外,用户还可能因为以下原因被踢出房间。
1. kick:当两个具有相同userId的用户进入同一个房间时,先进入的用户将被踢出。这是不允许的,因为这可能会导致双方之间的音频和视频通话异常,所以您应该避免这种情况的发生。
2. banned:通过服务端的 RemoveUser | RemoveUserByStrRoomId 接口将某个用户踢出某个 TRTC 房间,该用户会收到被踢事件,reason 为 banned .
3. room-disband:通过服务端的 DismissRoom | DismissRoomByStrRoomId接口将某个 TRTC 房间解散,解散房间之后,该房间的所有用户都会收到被踢事件,reason 为 room_disband。
trtc.on(TRTC.EVENT.KICKED_OUT, error => {console.error(`kicked out, reason:${error.reason}, message:${error.message}`);});
API 概述
TRTC 是TRTC SDK的主要入口, 提供创建trtc对象(TRTC.create), TRTC.getCameraList, TRTC.getMicrophoneList, TRTC.isSupported.
trtc 对象, 提供实时音视频通话的核心能力。
进入房间 trtc.enterRoom
退出房间 trtc.exitRoom
打开/关闭麦克风 trtc.startLocalAudio/trtc.stopLocalAudio
打开/关闭摄像头 trtc.startLocalVideo/trtc.stopLocalVideo
播放/停止远程音频 trtc.muteRemoteAudio
播放/停止远程视频 trtc.startRemoteVideo/trtc.stopRemoteVideo
API 全流程

