### Running TRTC React Native Demo on iOS
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README-zh_CN.md
This section outlines the commands for setting up and running the TRTC React Native Demo on an iOS device. It involves installing CocoaPods dependencies, starting the Metro bundler, and then running the application for iOS development.
```bash
# Install dependencies
npm install
# Install iOS dependencies
cd ios && pod install && cd ..
# Start Metro bundler
npx react-native start
# Run on iOS device
npx react-native run-ios
# If errors occur, open Xcode and build/debug from there.
```
--------------------------------
### Running TRTC React Native Demo on Android
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README-zh_CN.md
This section details the commands needed to compile and run the TRTC React Native Demo on an Android device. It includes starting the Metro bundler and then executing the React Native application for Android development.
```bash
# Install dependencies
npm install
# Start Metro bundler
npx react-native start
# Run on Android device
npx react-native run-android
```
--------------------------------
### Build and Run TRTC React Native Demo (iOS)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README.md
Details the steps to build and run the TRTC React Native demo on an iOS device or simulator. This includes installing npm dependencies, running `pod install` for native dependencies, starting the Metro bundler, and then executing the iOS build command.
```bash
npx react-native run-ios
```
--------------------------------
### iOS Permissions Configuration for TRTC SDK
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README-zh_CN.md
This snippet shows the required keys to be added to the `Info.plist` file for iOS applications using the TRTC SDK. These keys provide descriptions for camera and microphone usage, which are necessary for obtaining user consent to access these hardware components.
```objectivec
NSCameraUsageDescription
授权摄像头权限才能正常视频通话
NSMicrophoneUsageDescription
授权麦克风权限才能正常语音通话
```
--------------------------------
### Build and Run TRTC React Native Demo (Android)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README.md
Provides commands to build and run the TRTC React Native demo on an Android device or emulator. It involves installing dependencies, starting the Metro bundler, and then executing the Android build command.
```bash
npx react-native run-android
```
--------------------------------
### Requesting Android Audio and Camera Permissions in React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README-zh_CN.md
This JavaScript code demonstrates how to programmatically request the necessary audio and camera permissions on Android using the PermissionsAndroid module in React Native. These permissions are essential for the TRTC SDK's audio and video functionalities.
```javascript
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, //音频需要
PermissionsAndroid.PERMISSIONS.CAMERA, // 视频需要
]);
}
```
--------------------------------
### Start Metro Bundler for React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
This command starts the Metro bundler, which is essential for serving your JavaScript code to the React Native application during development. Ensure you are in your React Native project directory before running this command. No specific inputs or outputs are defined, as it's a background process.
```bash
npx react-native start
```
--------------------------------
### Configuring TRTC SDK App ID and Secret Key in React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README-zh_CN.md
This snippet illustrates how to configure the `SDKAPPID` and `SECRETKEY` within the `/src/debug/config.js` file for the TRTC React Native Demo. These credentials are required for the SDK to connect to Tencent Cloud services. It also includes a crucial security warning about storing the secret key client-side.
```javascript
// /src/debug/config.js
const TRTCAppInfo = {
SDKAPPID: PLACEHOLDER, // Replace with your actual SDKAppID
SECRETKEY: PLACEHOLDER, // Replace with your actual Secret Key
};
export default TRTCAppInfo;
// Security Warning:
// Storing SECRETKEY in client-side code is insecure and only suitable for local testing.
// For production, use server-side generation of UserSig.
```
--------------------------------
### TRTC SDK Event Listening
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Sets up and removes listeners for TRTC SDK events. It includes examples for handling room entry callbacks, remote user entry, and audio availability of remote users. This is crucial for real-time feedback and interaction.
```javascript
//设置事件监听
trtcCloud.registerListener(onRtcListener);
function onRtcListener(type: TRTCCloudListener, params: any) {
//进房回调事件
if (type === TRTCCloudListener.onEnterRoom) {
if (params.result > 0) {
//进房成功
}
}
// 远端用户进房
if (type === TRTCCloudListener.onRemoteUserEnterRoom) {
//params.userId参数为远端用户userId
}
//远端用户是否打开麦克风
if (type === TRTCCloudListener.onUserAudioAvailable) {
//param.userId 表示远端用户id
//param.visible true表示打开麦克风
}
}
//移除事件监听
trtcCloud.unRegisterListener(onRtcListener);
```
--------------------------------
### Configure SDK Credentials and Generate User Authentication Signatures
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
This snippet demonstrates how to configure SDK credentials (SDKAPPID, SECRETKEY, EXPIRETIME) and generate user authentication signatures (UserSig) using a provided JavaScript library. It includes examples for both client-side and server-side (Node.js) UserSig generation. In production environments, UserSig generation must be handled on a secure backend server to protect secret keys.
```javascript
// src/debug/config.js
const SDKAPPID = 1400000000; // Replace with your SDK App ID
const SECRETKEY = 'your_secret_key_here'; // Replace with your secret key
const EXPIRETIME = 604800; // 7 days in seconds
export { SDKAPPID, EXPIRETIME, SECRETKEY };
// src/debug/index.js
import { SDKAPPID, SECRETKEY, EXPIRETIME } from './config';
import LibGenerateTestUserSig from './lib-generate-test-usersig.min.js';
const generator = new LibGenerateTestUserSig(SDKAPPID, SECRETKEY, EXPIRETIME);
// Generate UserSig for a user
export default function getLatestUserSig(userID) {
const userSig = generator.genTestUserSig(userID);
return {
userSig,
privateMapKey: 255,
};
}
// Usage example
import getLatestUserSig from './debug';
function authenticateUser(userId) {
const { userSig } = getLatestUserSig(userId);
console.log('Generated UserSig for', userId);
return userSig;
}
// IMPORTANT: In production, implement server-side UserSig generation:
//
// Server-side (Node.js example):
// app.post('/api/getUserSig', (req, res) => {
// const { userId } = req.body;
// const userSig = generateUserSig(userId); // Server-side generation
// res.json({ userSig });
// });
//
// Client-side:
// async function getUserSig(userId) {
// const response = await fetch('/api/getUserSig', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ userId }),
// });
// const { userSig } = await response.json();
// return userSig;
// }
```
--------------------------------
### TRTC Event Listener Registration and Handling (JavaScript)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
Illustrates how to register and unregister a listener for TRTC events. The example shows how to handle callbacks for room entry, remote user entry, and remote user's audio availability.
```javascript
trtcCloud.registerListener(onRtcListener);
function onRtcListener(type, params) {
if (type === TRTCCloudListener.onEnterRoom) {
if (params.result > 0) {
}
}
if (type === TRTCCloudListener.onRemoteUserEnterRoom) {
}
if (type === TRTCCloudListener.onUserAudioAvailable) {
}
}
trtcCloud.unRegisterListener(onRtcListener);
```
--------------------------------
### Local Video Rendering with TXVideoView.LocalView
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Renders the local camera feed in a React Native application using the TXVideoView.LocalView component. This component automatically captures and displays the device camera with hardware acceleration. Ensure 'trtc-react-native' is installed as a dependency.
```javascript
import React from 'react';
import { View, StyleSheet } from 'react-native';
import { TXVideoView } from 'trtc-react-native';
function VideoCallScreen() {
return (
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000',
},
localVideo: {
width: '100%',
height: '100%',
},
});
export default VideoCallScreen;
```
--------------------------------
### Remote Video Rendering with TXVideoView.RemoteView
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Displays video streams from remote users in a React Native application using TXVideoView.RemoteView. It supports rendering both the main video stream (TRTC_VIDEO_STREAM_TYPE_BIG) and sub-streams like screen sharing (TRTC_VIDEO_STREAM_TYPE_SUB). The component handles automatic rendering of these streams. Requires 'trtc-react-native' to be installed.
```javascript
import React, { useState } from 'react';
import { View, ScrollView, StyleSheet, Text } from 'react-native';
import { TXVideoView, TRTCCloudDef } from 'trtc-react-native';
function RemoteUsersView({ remoteUsers }) {
return (
{remoteUsers.map((user) => (
{/* Render main video stream */}
{user.userId}
))}
);
}
function ScreenShareView({ userId }) {
return (
{/* Render screen sharing stream */}
);
}
const styles = StyleSheet.create({
remoteContainer: {
flexDirection: 'row',
},
remoteViewItem: {
width: 120,
height: 160,
margin: 5,
backgroundColor: '#333',
borderRadius: 8,
overflow: 'hidden',
},
remoteVideo: {
width: '100%',
height: '100%',
},
userLabel: {
position: 'absolute',
bottom: 5,
left: 5,
color: 'white',
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 3,
fontSize: 10,
},
screenShareContainer: {
flex: 1,
},
screenShareVideo: {
width: '100%',
height: '100%',
},
});
```
--------------------------------
### Initialize TRTC SDK and Access Managers (JavaScript)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
Demonstrates how to create a singleton instance of TRTCCloud, and obtain instances for device and audio effect management. This is a prerequisite for using most TRTC functionalities.
```javascript
const trtcCloud = TRTCCloud.sharedInstance();
const txDeviceManager = trtcCloud.getDeviceManager();
const txAudioManager = trtcCloud.getAudioEffectManager();
```
--------------------------------
### TRTCCloud Initialization and Module Access (JavaScript)
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Initializes the TRTCCloud singleton instance, which is the primary interface for all SDK operations. It also demonstrates how to access device management and audio effect management modules. This initialization must precede any other SDK method calls.
```javascript
import TRTCCloud, {
TRTCCloudDef,
TRTCCloudListener,
TXVideoView
} from 'trtc-react-native';
// Initialize TRTC Cloud singleton
const trtcCloud = TRTCCloud.sharedInstance();
// Get device management module
const txDeviceManager = trtcCloud.getDeviceManager();
// Get audio effect management module
const txAudioManager = trtcCloud.getAudioEffectManager();
```
--------------------------------
### Initialize TRTC SDK and Managers
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Initializes the TRTCCloud singleton and obtains instances for device management, audio effects, and beauty management. This is a prerequisite for using most TRTC functionalities.
```javascript
// 创建 TRTCCloud 单例
const trtcCloud = TRTCCloud.sharedInstance();
// 获取设备管理模块
const txDeviceManager = trtcCloud.getDeviceManager();
// 获取音效管理类
const txAudioManager = trtcCloud.getAudioEffectManager();
// 获取美颜管理类
const txBeautyManager = trtcCloud.getBeautyManager();
```
--------------------------------
### Room Entry and Exit with TRTCParams (JavaScript)
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Joins a TRTC room using specified parameters including SDK App ID, user credentials, and room ID. The scene type optimizes communication settings. It also shows how to exit the room. UserSig generation should be handled server-side in production environments.
```javascript
import TRTCCloud, { TRTCParams, TRTCCloudDef } from 'trtc-react-native';
import getLatestUserSig from './debug';
const trtcCloud = TRTCCloud.sharedInstance();
// Configuration parameters
const SDKAPPID = 1400000000; // Your SDK App ID
const userId = 'user_123';
const roomId = 2366;
// Generate UserSig (should be done server-side in production)
const { userSig } = getLatestUserSig(userId);
// Create room parameters
const params = new TRTCParams({
sdkAppId: SDKAPPID,
userId: userId,
userSig: userSig,
roomId: roomId,
});
// Enter room for video call scenario
trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL)
.then(() => console.log('Entered room successfully'))
.catch((error) => console.error('Failed to enter room:', error));
// Exit room when done
trtcCloud.exitRoom()
.then(() => console.log('Exited room successfully'))
.catch((error) => console.error('Failed to exit room:', error));
```
--------------------------------
### Configure iOS Application Permissions (Objective-C)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README.md
Configures essential application permissions for camera and microphone access required by the TRTC SDK on iOS. These keys are added to the `Info.plist` file to ensure the application can utilize these hardware components for video and audio calls.
```objectivec
NSCameraUsageDescription
Video calls are possible only with camera permission.
NSMicrophoneUsageDescription
Audio calls are possible only with mic access.
```
--------------------------------
### Android Manifest Permissions for TRTC
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/QuickIntegration.md
Declare necessary permissions in `AndroidManifest.xml` for the TRTC SDK on Android. This includes permissions for internet access, storage, audio recording, and camera usage. Hardware acceleration should not be disabled.
```xml
```
--------------------------------
### Manage Camera and Audio Devices in TRTC React Native
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Provides functions to control camera and audio device settings, including switching between front and rear cameras, checking the current camera status, and setting the audio route to speaker or earpiece. Dependencies include 'react-native' and 'trtc-react-native'.
```javascript
import { Platform } from 'react-native';
import TRTCCloud, { TRTCCloudDef } from 'trtc-react-native';
const trtcCloud = TRTCCloud.sharedInstance();
const deviceManager = trtcCloud.getDeviceManager();
// Switch between front and rear camera
async function switchCamera() {
try {
const isFront = await deviceManager.isFrontCamera();
await deviceManager.switchCamera(!isFront);
console.log('Switched to', !isFront ? 'front' : 'back', 'camera');
return !isFront;
} catch (error) {
console.error('Failed to switch camera:', error);
throw error;
}
}
// Check current camera
async function checkCamera() {
try {
const isFront = await deviceManager.isFrontCamera();
console.log('Current camera:', isFront ? 'front' : 'back');
return isFront;
} catch (error) {
console.error('Failed to check camera:', error);
throw error;
}
}
// Set audio route (speaker or earpiece)
async function setAudioRoute(useSpeaker) {
try {
const route = useSpeaker
? TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER
: TRTCCloudDef.TRTC_AUDIO_ROUTE_EARPIECE;
await deviceManager.setAudioRoute(route);
console.log('Audio route set to', useSpeaker ? 'speaker' : 'earpiece');
} catch (error) {
console.error('Failed to set audio route:', error);
throw error;
}
}
// Complete device management example
async function setupDevices() {
try {
// Check front camera status
const isFront = await deviceManager.isFrontCamera();
console.log('Camera is', isFront ? 'front' : 'back');
// Set to speaker mode for video calls
await deviceManager.setAudioRoute(TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER);
return { isFrontCamera: isFront };
} catch (error) {
console.error('Device setup failed:', error);
throw error;
}
}
```
--------------------------------
### iOS Info.plist Permissions for TRTC
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/QuickIntegration.md
Configure `Info.plist` on iOS to request camera and microphone permissions for voice and video calls. This is a requirement for the TRTC SDK to function correctly.
```xml
NSCameraUsageDescription
Video calls require camera permission.
NSMicrophoneUsageDescription
Voice calls require microphone permission.
```
--------------------------------
### Enter and Exit TRTC Room (JavaScript)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
Shows how to join a TRTC room using SDKAppID, UserID, UserSig, and RoomID, specifying the application scene. It also includes the method to leave the current room.
```javascript
const params = new TRTCParams({
sdkAppId: SDKAPPID,
userId: userId,
userSig: userSig,
roomId: 2366,
});
trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);
trtcCloud.exitRoom();
```
--------------------------------
### Add TRTC React Native Dependency
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/QuickIntegration.md
This snippet shows how to add the 'trtc-react-native' package to your project's dependencies in `package.json`. Ensure your React Native version is 0.63 or above and Node.js is v12 or higher.
```bash
"dependencies": {
"trtc-react-native": "^2.5.0"
},
```
--------------------------------
### Request Audio/Video Permissions on Android
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/QuickIntegration.md
Manually request audio and camera permissions on Android using `PermissionsAndroid.requestMultiple`. This is crucial for enabling voice and video call functionalities within the TRTC SDK.
```javascript
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, //For audio calls
PermissionsAndroid.PERMISSIONS.CAMERA, // For video calls
]);
}
```
--------------------------------
### TRTC React Native Live Streaming Roles
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Enables entering and managing live streaming rooms with either an anchor (broadcaster) or audience (viewer) role using `trtc-react-native`. It handles entering rooms, publishing/subscribing to streams, and switching roles dynamically.
```javascript
import TRTCCloud, { TRTCParams, TRTCCloudDef } from 'trtc-react-native';
import getLatestUserSig from './debug';
const trtcCloud = TRTCCloud.sharedInstance();
// Enter room as anchor (broadcaster)
async function enterAsAnchor(roomId, userId) {
try {
const { userSig } = getLatestUserSig(userId);
const params = new TRTCParams({
sdkAppId: SDKAPPID,
userId: userId,
userSig: userSig,
roomId: roomId,
role: TRTCCloudDef.TRTCRoleAnchor, // Set as anchor
});
await trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
// Start publishing audio and video
await trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
// Video is started automatically by TXVideoView.LocalView
console.log('Entered as anchor');
} catch (error) {
console.error('Failed to enter as anchor:', error);
throw error;
}
}
// Enter room as audience (viewer)
async function enterAsAudience(roomId, userId) {
try {
const { userSig } = getLatestUserSig(userId);
const params = new TRTCParams({
sdkAppId: SDKAPPID,
userId: userId,
userSig: userSig,
roomId: roomId,
role: TRTCCloudDef.TRTCRoleAudience, // Set as audience
});
await trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
// Audience doesn't publish, only subscribes to anchor streams
console.log('Entered as audience');
} catch (error) {
console.error('Failed to enter as audience:', error);
throw error;
}
}
// Switch role during live streaming
async function switchRole(newRole) {
try {
await trtcCloud.switchRole(newRole);
if (newRole === TRTCCloudDef.TRTCRoleAnchor) {
// Start publishing when becoming anchor
await trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
console.log('Switched to anchor role');
} else {
// Stop publishing when becoming audience
await trtcCloud.stopLocalAudio();
console.log('Switched to audience role');
}
} catch (error) {
console.error('Failed to switch role:', error);
throw error;
}
}
```
--------------------------------
### Enter and Exit TRTC Room
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Demonstrates how to enter and exit a TRTC room using provided parameters such as SDK App ID, user ID, user signature, and room ID. It utilizes `TRTCParams` and specifies the application scene.
```javascript
const params = new TRTCParams({
sdkAppId: SDKAPPID, //应用id
userId, //用户id
userSig, //用户签名
roomId: 2366, //房间Id
});
//进房
trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL);
//退房
trtcCloud.exitRoom();
```
--------------------------------
### Android App Permissions for TRTC
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Specifies the necessary Android permissions required for the TRTC SDK to function, including internet access, network state, audio recording, camera usage, and storage permissions. It also includes a code snippet for requesting runtime permissions for audio and camera on Android.
```xml
```
```javascript
// 安卓音视频权限需要手动申请
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, //音频需要
PermissionsAndroid.PERMISSIONS.CAMERA, // 视频需要
]);
}
```
--------------------------------
### Request Audio and Camera Permissions in React Native (Android)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/TRTC-Simple-Demo/README.md
This JavaScript code snippet demonstrates how to programmatically request essential audio and camera permissions from the user on Android devices within a React Native application. This is crucial for enabling audio and video functionalities in the TRTC demo.
```javascript
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO, //For audio calls
PermissionsAndroid.PERMISSIONS.CAMERA, // For video calls
]);
}
```
--------------------------------
### Configure Video Encoder Settings in TRTC React Native
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Sets video encoding parameters such as resolution, frame rate, and bitrate to optimize video quality and bandwidth usage. It also includes functions to enable/disable mirror mode and apply predefined quality presets. Dependencies include 'trtc-react-native'.
```javascript
import TRTCCloud, { TRTCCloudDef } from 'trtc-react-native';
const trtcCloud = TRTCCloud.sharedInstance();
// Configure video encoding parameters
async function configureVideoEncoder() {
try {
await trtcCloud.setVideoEncoderParam({
videoFps: 15, // Frame rate
videoResolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360,
minVideoBitrate: 0,
videoBitrate: 800, // Bitrate in kbps
enableAdjustRes: false,
videoResolutionMode: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT,
});
console.log('Video encoder configured');
} catch (error) {
console.error('Failed to configure encoder:', error);
}
}
// Set video encoder mirror
async function setMirror(enableMirror) {
try {
await trtcCloud.setVideoEncoderMirror(enableMirror);
console.log('Mirror mode:', enableMirror ? 'ON' : 'OFF');
} catch (error) {
console.error('Failed to set mirror:', error);
}
}
// Resolution and bitrate presets
const VIDEO_CONFIGS = {
LOW: {
resolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360,
fps: 15,
bitrate: 800,
},
MEDIUM: {
resolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_960_540,
fps: 20,
bitrate: 900,
},
HIGH: {
resolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720,
fps: 20,
bitrate: 1250,
},
ULTRA: {
resolution: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1920_1080,
fps: 30,
bitrate: 1900,
},
};
// Apply preset configuration
async function applyVideoPreset(preset) {
const config = VIDEO_CONFIGS[preset];
try {
await trtcCloud.setVideoEncoderParam({
videoFps: config.fps,
videoResolution: config.resolution,
videoBitrate: config.bitrate,
minVideoBitrate: 0,
enableAdjustRes: false,
videoResolutionMode: TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT,
});
console.log(`Applied ${preset} quality preset`);
} catch (error) {
console.error('Failed to apply preset:', error);
}
}
```
--------------------------------
### Re-run iOS Application Build
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
This command is a shortcut to re-run the iOS build, typically used after making changes to the native iOS directory or related configurations. It's equivalent to running `yarn ios` and is useful for updating the application on the simulator or device.
```bash
yarn ios
```
--------------------------------
### React Native Video Call with TRTC SDK
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Implements a video call room component for React Native applications using the TRTC SDK. It manages user states, handles real-time audio and video, and provides controls for microphone and camera. Dependencies include 'trtc-react-native' and 'react-native'.
```javascript
import React, { useState, useEffect, useCallback } from 'react';
import { View, StyleSheet, TouchableOpacity, Text, Alert } from 'react-native';
import TRTCCloud, {
TRTCCloudListener,
TRTCCloudDef,
TXVideoView,
TRTCParams
} from 'trtc-react-native';
import getLatestUserSig from './debug';
function VideoCallRoom({ roomId, localUserId, onExit }) {
const [remoteUsers, setRemoteUsers] = useState([]);
const [isMicOpen, setIsMicOpen] = useState(true);
const [isFrontCamera, setIsFrontCamera] = useState(true);
const onRtcListener = useCallback((type, params) => {
if (type === TRTCCloudListener.onRemoteUserEnterRoom) {
setRemoteUsers(prev => [...prev, {
userId: params.userId,
videoAvailable: false
}]);
} else if (type === TRTCCloudListener.onRemoteUserLeaveRoom) {
setRemoteUsers(prev =>
prev.filter(user => user.userId !== params.userId)
);
} else if (type === TRTCCloudListener.onUserVideoAvailable) {
setRemoteUsers(prev => prev.map(user =>
user.userId === params.userId
? { ...user, videoAvailable: params.available }
: user
));
}
}, []);
useEffect(() => {
const trtcCloud = TRTCCloud.sharedInstance();
const { userSig } = getLatestUserSig(localUserId);
// Enter room
const params = new TRTCParams({
sdkAppId: SDKAPPID,
userId: localUserId,
userSig: userSig,
roomId: parseInt(roomId),
});
trtcCloud.enterRoom(params, TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL)
.then(() => {
console.log('Entered room');
return trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
})
.catch(error => {
console.error('Room entry failed:', error);
Alert.alert('Error', 'Failed to join room');
});
trtcCloud.registerListener(onRtcListener);
return () => {
trtcCloud.unRegisterListener(onRtcListener);
trtcCloud.stopLocalAudio();
trtcCloud.exitRoom();
};
}, [roomId, localUserId, onRtcListener]);
const handleMicToggle = async () => {
const trtcCloud = TRTCCloud.sharedInstance();
try {
await trtcCloud.muteLocalAudio(isMicOpen);
setIsMicOpen(!isMicOpen);
} catch (error) {
Alert.alert('Error', 'Failed to toggle microphone');
}
};
const handleCameraSwitch = async () => {
const trtcCloud = TRTCCloud.sharedInstance();
try {
await trtcCloud.getDeviceManager().switchCamera(!isFrontCamera);
setIsFrontCamera(!isFrontCamera);
} catch (error) {
Alert.alert('Error', 'Failed to switch camera');
}
};
const handleExit = async () => {
const trtcCloud = TRTCCloud.sharedInstance();
try {
await trtcCloud.stopLocalAudio();
await trtcCloud.exitRoom();
onExit();
} catch (error) {
Alert.alert('Error', 'Failed to exit room');
}
};
return (
{localUserId} (Me)
{remoteUsers.map(user => (
user.videoAvailable && (
{user.userId}
)
))}
{isMicOpen ? 'Mute' : 'Unmute'}
Switch Camera
Exit
);
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: '#000' },
localView: { flex: 1 },
video: { flex: 1 },
label: {
position: 'absolute',
bottom: 5,
left: 5,
color: 'white',
backgroundColor: 'rgba(0,0,0,0.5)',
padding: 5
},
remoteViews: {
flexDirection: 'row',
height: 120,
backgroundColor: '#333'
},
remoteView: {
width: 100,
height: 100,
margin: 10
},
controls: {
// Styles for controls container would be here
}
});
```
--------------------------------
### Request Android Camera and Microphone Permissions
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Requests camera and microphone permissions on Android devices before initializing audio/video capture. It uses `PermissionsAndroid` and alerts the user if permissions are denied. iOS permissions are managed via `Info.plist`.
```javascript
import { Platform, PermissionsAndroid, Alert } from 'react-native';
// Android permission request
async function requestAndroidPermissions() {
if (Platform.OS === 'android') {
try {
const grants = await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
PermissionsAndroid.PERMISSIONS.CAMERA,
]);
const audioGranted = grants['android.permission.RECORD_AUDIO'] ===
PermissionsAndroid.RESULTS.GRANTED;
const cameraGranted = grants['android.permission.CAMERA'] ===
PermissionsAndroid.RESULTS.GRANTED;
if (!audioGranted || !cameraGranted) {
Alert.alert(
'Permissions Required',
'Camera and microphone permissions are required for video calls'
);
return false;
}
console.log('All permissions granted');
return true;
} catch (error) {
console.error('Permission request failed:', error);
return false;
}
}
return true; // iOS handles permissions automatically
}
// iOS permissions are configured in Info.plist:
// NSCameraUsageDescription
// Video calls are possible only with camera permission.
// NSMicrophoneUsageDescription
// Audio calls are possible only with mic access.
// Use in app initialization
import React, { useEffect } from 'react';
function App() {
useEffect(() => {
requestAndroidPermissions();
}, []);
return (
// App components
);
}
```
--------------------------------
### Request Audio and Video Permissions on Android (JavaScript)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
Shows how to programmatically request essential audio and camera permissions on Android devices using the `PermissionsAndroid` module. This is crucial for enabling calls and video functionality.
```javascript
if (Platform.OS === 'android') {
await PermissionsAndroid.requestMultiple([
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
]);
}
```
--------------------------------
### iOS Application Permissions Configuration (Plist)
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README.md
Specifies the required privacy permissions for camera and microphone usage in the `Info.plist` file for iOS applications integrating the TRTC SDK. These keys inform the user why the app needs access.
```plist
NSCameraUsageDescription
Authorize the camera permission to make a normal video call
NSMicrophoneUsageDescription
Authorize microphone permissions to make normal voice calls
```
--------------------------------
### Audio Control Functions in TRTC React Native
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Manages local audio capture and playback within a React Native TRTC application. This includes starting/stopping the microphone, muting audio, adjusting volume levels for capture and playback, and managing remote user audio. Requires 'trtc-react-native' and TRTCCloudDef. Uses the TRTCCloud.sharedInstance() for all operations.
```javascript
import TRTCCloud, { TRTCCloudDef } from 'trtc-react-native';
const trtcCloud = TRTCCloud.sharedInstance();
// Start local audio with default quality
async function startAudio() {
try {
await trtcCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
console.log('Started local audio');
} catch (error) {
console.error('Failed to start audio:', error);
}
}
// Stop local audio
async function stopAudio() {
try {
await trtcCloud.stopLocalAudio();
console.log('Stopped local audio');
} catch (error) {
console.error('Failed to stop audio:', error);
}
}
// Mute/unmute local audio
async function toggleMute(shouldMute) {
try {
await trtcCloud.muteLocalAudio(shouldMute);
console.log(shouldMute ? 'Muted audio' : 'Unmuted audio');
} catch (error) {
console.error('Failed to toggle mute:', error);
}
}
// Set audio capture volume (0-100)
async function setCaptureVolume(volume) {
try {
await trtcCloud.setAudioCaptureVolume(volume);
console.log('Set capture volume to', volume);
} catch (error) {
console.error('Failed to set capture volume:', error);
}
}
// Set audio playout volume (0-100)
async function setPlayoutVolume(volume) {
try {
await trtcCloud.setAudioPlayoutVolume(volume);
console.log('Set playout volume to', volume);
} catch (error) {
console.error('Failed to set playout volume:', error);
}
}
// Enable audio volume callback (interval in ms, 0 to disable)
trtcCloud.enableAudioVolumeEvaluation(300);
// Mute all remote audio
async function muteAllRemote(shouldMute) {
try {
await trtcCloud.muteAllRemoteAudio(shouldMute);
console.log(shouldMute ? 'Muted all remote' : 'Unmuted all remote');
} catch (error) {
console.error('Failed to mute all remote:', error);
}
}
// Mute specific remote user
async function muteRemoteUser(userId, shouldMute) {
try {
await trtcCloud.muteRemoteAudio(userId, shouldMute);
console.log(`${shouldMute ? 'Muted' : 'Unmuted'} user ${userId}`);
} catch (error) {
console.error('Failed to mute remote user:', error);
}
}
```
--------------------------------
### TRTC Event Listener Registration and Handling (JavaScript)
Source: https://context7.com/tencent-rtc/trtc_reactnative/llms.txt
Registers callbacks to manage various TRTC events, such as room entry success/failure, remote user presence changes, audio/video availability, and network quality updates. This is crucial for dynamically updating the UI based on real-time room activities. Callbacks can be unregistered when no longer needed.
```javascript
import TRTCCloud, { TRTCCloudListener } from 'trtc-react-native';
const trtcCloud = TRTCCloud.sharedInstance();
function onRtcListener(type, params) {
// Handle successful room entry
if (type === TRTCCloudListener.onEnterRoom) {
if (params.result > 0) {
console.log('Successfully entered room, elapsed time:', params.result, 'ms');
} else {
console.error('Failed to enter room, error code:', params.result);
}
}
// Handle remote user entering room
if (type === TRTCCloudListener.onRemoteUserEnterRoom) {
console.log('Remote user entered:', params.userId);
// Update UI to show new user
}
// Handle remote user leaving room
if (type === TRTCCloudListener.onRemoteUserLeaveRoom) {
console.log('Remote user left:', params.userId);
// Update UI to remove user
}
// Handle remote user's audio availability
if (type === TRTCCloudListener.onUserAudioAvailable) {
console.log(`User ${params.userId} audio:`, params.available ? 'ON' : 'OFF');
}
// Handle remote user's video availability
if (type === TRTCCloudListener.onUserVideoAvailable) {
console.log(`User ${params.userId} video:`, params.available ? 'ON' : 'OFF');
}
// Handle network quality updates
if (type === TRTCCloudListener.onNetworkQuality) {
console.log('Local quality:', params.localQuality.quality);
params.remoteQuality.forEach((remote) => {
console.log(`User ${remote.userId} quality:`, remote.quality);
});
}
}
// Register the listener
trtcCloud.registerListener(onRtcListener);
// Unregister when component unmounts
trtcCloud.unRegisterListener(onRtcListener);
```
--------------------------------
### Display Local Video in React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Renders the local user's video stream within the React Native application using the `TXVideoView.LocalView` component. This is a straightforward way to display the camera feed.
```javascript
```
--------------------------------
### Display Remote Screen Share in React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Renders a remote user's screen share stream. This is achieved by using the `TXVideoView.RemoteView` component and specifying `TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SUB` for the `streamType`.
```javascript
```
--------------------------------
### Display Remote Video in React Native
Source: https://github.com/tencent-rtc/trtc_reactnative/blob/main/SDK/README-zh_CN.md
Displays a remote user's video stream by specifying their `userId` and the `streamType`. Supports rendering both the main video stream and screen sharing (sub stream).
```javascript
```