tencent_rtc_sdk).Platform | Android | iOS | Windows | macOS |
Supported | | | | |

UserSig (the authentication credential for a user to enter an audio/video room).userId in the UserSig generation tool under Auxiliary Tools in the console to generate a temporary UserSig. You can also calculate it locally by referring to User Authentication.flutter pub add tencent_rtc_sdk
flutter pub add permission_handler
pubspec.yaml file and add the tencent_rtc_sdk (to find the latest version, see https://pub.dev/packages/tencent_rtc_sdk) and permission_handler dependencies:dependencies:# TRTC Flutter SDK dependency. Replace it with the latest version on pub.devtencent_rtc_sdk: ^<latest version># Permission handling plugin dependencypermission_handler: ^11.0.0
pubspec.yaml):flutter pub get
ios/Runner/Info.plist. When the SDK accesses the camera and microphone for the first time, the system automatically displays an authorization dialog:<key>NSCameraUsageDescription</key><string>Camera permission is required for video calls</string><key>NSMicrophoneUsageDescription</key><string>Microphone permission is required for voice calls</string>
Permission.camera.request() returns "denied" directly without showing the system authorization dialog. Merge the following content into the existing post_install in ios/Podfile, and do not declare post_install again:post_install do |installer|installer.pods_project.targets.each do |target|flutter_additional_ios_build_settings(target)target.build_configurations.each do |config|config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)',## permission_handler: enable camera permission'PERMISSION_CAMERA=1',## permission_handler: enable microphone permission'PERMISSION_MICROPHONE=1',]endendend
symbol not found error at runtime in Release while Debug works normally. In Xcode, choose Runner > TARGETS > Runner > Build Settings, and change the following two settings under the Release configuration:Yes.
Non-Global Symbols.
android/app/src/main/AndroidManifest.xml file.<uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /><uses-permission android:name="android.permission.CAMERA" /><!-- Bluetooth headset support: use BLUETOOTH on Android 11 and below, and BLUETOOTH_CONNECT on Android 12 and above --><uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" /><uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /><uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
libliteavsdk.so, a duplicate .so error occurs at build time. Add the following to android/app/build.gradle (or build.gradle.kts):// build.gradle (Groovy)android {packagingOptions {pickFirst 'lib/**/libliteavsdk.so'}}
// build.gradle.kts (Kotlin DSL)android {packaging {jniLibs {pickFirsts += "lib/**/libliteavsdk.so"}}}
minifyEnabled true), add the following rule to android/app/proguard-rules.pro, and make sure proguardFiles in buildTypes.release references this file:-keep class com.tencent.** { *; }
macos/Runner/Info.plist:<key>NSCameraUsageDescription</key><string>Camera permission is required for video calls</string><key>NSMicrophoneUsageDescription</key><string>Microphone permission is required for voice calls</string>
macos/Runner/DebugProfile.entitlements and macos/Runner/Release.entitlements. Otherwise, the app cannot access the camera, microphone, and network:<key>com.apple.security.device.camera</key><true/><key>com.apple.security.device.audio-input</key><true/><key>com.apple.security.network.client</key><true/>
.xcworkspace project file, click Project Navigator on the left side of the Xcode navigation bar, click Runner, and make sure the correct TARGETS is selected in the editor area.General tab, add ScreenCaptureKit.framework to the Frameworks, Libraries, and Embedded Content section.
import 'package:tencent_rtc_sdk/trtc_cloud.dart';import 'package:tencent_rtc_sdk/trtc_cloud_def.dart';import 'package:tencent_rtc_sdk/trtc_cloud_listener.dart';
late TRTCCloud trtcCloud;late TRTCCloudListener listener;
initState), create the TRTC instance and register event listeners. We recommend registering all required callbacks at once before entering the room:Future<void> initTRTC() async {// Create the TRTC instance (singleton)trtcCloud = await TRTCCloud.sharedInstance();// Create a TRTCCloudListener instance and implement the required callbackslistener = TRTCCloudListener(// Unrecoverable SDK errors, such as room entry failure or device open failureonError: (errCode, errMsg) {debugPrint('onError: $errCode, $errMsg');},// Room entry result: result > 0 means success (the value is the time taken, in ms); result < 0 is an error codeonEnterRoom: (result) {debugPrint(result > 0 ? 'Entered room successfully' : 'Failed to enter room: $result');},// A remote user turns video on / off. See Step 7 for detailsonUserVideoAvailable: (userId, available) {onRemoteVideoChanged(userId, available);},// Room exit completed. See Step 9 for detailsonExitRoom: (reason) {releaseTRTC();},);// Register the listener and bind it to the trtcCloud instancetrtcCloud.registerListener(listener);}
import 'dart:io';import 'package:permission_handler/permission_handler.dart';Future<bool> requestPermissions() async {if (!(Platform.isAndroid || TRTCPlatform.isOhos)) return true;final statuses = await [Permission.camera, Permission.microphone].request();return statuses.values.every((status) => status.isGranted);}
enterRoom to enter the room.Parameter | Type | Description |
sdkAppId | int | |
userId | String | The user ID you specify. It must be unique within the same room. |
userSig | String | |
strRoomId / roomId | String / int | The room ID. Specify one of the two. If both are specified, roomId takes precedence. The value range of roomId is 1 to 4294967294. strRoomId can be up to 64 bytes long and supports only the following characters: uppercase and lowercase letters (a-z, A-Z), digits (0-9), spaces, and ! # $ % & ( ) + - : ; < = . > ? @ [ ] ^ _ { } | ~ ,. Including other characters, such as Chinese characters, causes room entry to fail. |
scene | TRTCAppScene | The application scenario, which is the second parameter of enterRoom. For audio/video calls, use videoCall / audioCall. For interactive live streaming, use live / voiceChatRoom, and specify the anchor or audience role through TRTCParams.role. |
trtcCloud.enterRoom(TRTCParams(sdkAppId: sdkAppId, // Replace with your SDKAppIDuserId: userId, // Replace with your userIduserSig: userSig, // Replace with the UserSig corresponding to this userIdstrRoomId: roomId, // Replace with your room ID),TRTCAppScene.videoCall,);
sdkAppId, the same room ID, and different userId values (using the same userId on multiple devices to enter the same audio/video room at the same time is not supported).sdkAppId, use either numeric room IDs or string room IDs consistently, and do not mix them: the number 123 and the string "123" are two different rooms.enterRoom must be paired with exitRoom.TRTCCloudVideoView to the build method of your page. After obtaining the viewId in the onViewCreated callback, call startLocalPreview to start the camera preview:import 'package:tencent_rtc_sdk/trtc_cloud_video_view.dart';
TRTCCloudVideoView(key: const ValueKey('local'),onViewCreated: (viewId) {// true: front camera; false: rear camera (choose one; mobile only)trtcCloud.startLocalPreview(true, viewId);},),
viewId is the unique identifier of the video rendering widget TRTCCloudVideoView. It is available only after the onViewCreated callback, so startLocalPreview must be called in (or after) this callback.TRTCCloudVideoView only after TRTCCloud.sharedInstance() completes. The SDK determines the rendering method when the instance is created (macOS / Windows use texture rendering), so a widget created too early may fail to display video correctly.startLocalPreview to start the camera preview, you can call setLocalRenderParams to set the rendering parameters of the local preview:Parameter | Parameter Description | Value | Value Description |
rotation | The clockwise rotation angle of the image. Rotation angles of 90, 180, and 270 degrees are supported. Default value: TRTCVideoRotation.rotation0. | TRTCVideoRotation.rotation0 | No rotation. |
| | TRTCVideoRotation.rotation90 | Rotate 90 degrees clockwise. |
| | TRTCVideoRotation.rotation180 | Rotate 180 degrees clockwise. |
| | TRTCVideoRotation.rotation270 | Rotate 270 degrees clockwise. |
fillMode | The image fill mode: fill (the image may be stretched and cropped) or fit (the image may have black bars). Default value: TRTCVideoFillMode.fill. | TRTCVideoFillMode.fill | Fill mode: the image is centered and scaled proportionally to fill the entire display area. Any part beyond the display area is cropped, so the image may be incomplete in this mode. |
| | TRTCVideoFillMode.fit | Fit mode: the image is scaled according to its longer side to fit the display area, and the shorter side is filled with black. The image is complete in this mode but may have black bars. |
| | TRTCVideoFillMode.scaleFill | Scale-fill mode: regardless of the aspect ratio, the image is stretched or compressed to completely fill the display area. The aspect ratio may change in this mode, causing the rendered image to be distorted. |
mirrorType | The image mirror mode. Default value: TRTCVideoMirrorType.auto. | TRTCVideoMirrorType.auto | Auto mode: mirroring is enabled when the front camera is in use and disabled when the rear camera is in use (applicable to mobile devices only). |
| | TRTCVideoMirrorType.enable | Mirroring is forcibly enabled, regardless of whether the front or rear camera is in use. |
| | TRTCVideoMirrorType.disable | Mirroring is forcibly disabled, regardless of whether the front or rear camera is in use. |
// Set the rendering parameters of the local previewtrtcCloud.setLocalRenderParams(TRTCRenderParams(fillMode: TRTCVideoFillMode.fill,mirrorType: TRTCVideoMirrorType.auto,rotation: TRTCVideoRotation.rotation0,),);
stopLocalPreview to turn off the camera preview and stop publishing local video.trtcCloud.stopLocalPreview();
TXDeviceManager class to implement extended device features such as "switch between front and rear cameras", "set focus mode", and "flashlight".import 'package:tencent_rtc_sdk/tx_device_manager.dart';
// Get the device manager instanceTXDeviceManager manager = trtcCloud.getDeviceManager();// Switch between front and rear cameras: if the front camera is in use, switch to the rear camera, and vice versamanager.switchCamera(!manager.isFrontCamera());
// Get the device manager instanceTXDeviceManager manager = trtcCloud.getDeviceManager();// If the device supports auto focus (automatic face detection), enable auto focusif (manager.isAutoFocusEnabled()) {manager.enableCameraAutoFocus(true);}
// Get the device manager instanceTXDeviceManager manager = trtcCloud.getDeviceManager();// Turn on the flashlight (effective only when the rear camera is in use)manager.enableCameraTorch(true);// Turn off the flashlightmanager.enableCameraTorch(false);
startLocalAudio to start microphone capture. Based on your needs, choose one of the following audio quality parameters:Parameter | Description |
TRTCAudioQuality.speech | Speech mode: mono; encoding bitrate: 16 kbps; it has the strongest weak-network resilience among the modes and is suitable for scenarios dominated by voice, such as online meetings and voice calls. |
TRTCAudioQuality.defaultMode | Default mode: mono; encoding bitrate: 50 kbps; a level between speech and music, and the SDK default. Recommended. |
TRTCAudioQuality.music | Music mode: full-band stereo; encoding bitrate: 128 kbps; suitable for scenarios that require high-fidelity music transmission, such as online karaoke and music live streaming. |
// Start microphone capture with the default audio quality (recommended)trtcCloud.startLocalAudio(TRTCAudioQuality.defaultMode);
// For voice-dominated scenarios (such as online meetings), you can use speech mode for stronger weak-network resiliencetrtcCloud.startLocalAudio(TRTCAudioQuality.speech);
stopLocalAudio to turn off microphone capture and stop publishing local audio.trtcCloud.stopLocalAudio();
onUserVideoAvailable callback in the listener registered in Step 3. When onUserVideoAvailable(userId, true) is received, it means playable video frames from that user have arrived, and you can add a rendering widget for that user. When false is received, stop playback and remove the widget.final List<String> remoteUsers = [];void onRemoteVideoChanged(String userId, bool available) {if (!mounted) return;setState(() {if (available) {if (!remoteUsers.contains(userId)) remoteUsers.add(userId);} else {remoteUsers.remove(userId);trtcCloud.stopRemoteView(userId, TRTCVideoStreamType.big);}});}
build method, create a TRTCCloudVideoView for each remote user, and call startRemoteView in the onViewCreated callback to play that user's video:for (final userId in remoteUsers)TRTCCloudVideoView(key: ValueKey('remote_$userId'),onViewCreated: (viewId) {// Play the remote user's primary (big) video streamtrtcCloud.startRemoteView(userId, TRTCVideoStreamType.big, viewId);},),
stopAllRemoteView to stop playing the videos of all remote users.// Stop playing the video of all remote userstrtcCloud.stopAllRemoteView();
muteRemoteAudio / muteAllRemoteAudio:// Mute a specific remote user (remoteUserId is the userId of the remote user)trtcCloud.muteRemoteAudio(remoteUserId, true);// Mute all remote userstrtcCloud.muteAllRemoteAudio(true);
// Unmute a specific remote usertrtcCloud.muteRemoteAudio(remoteUserId, false);// Unmute all remote userstrtcCloud.muteAllRemoteAudio(false);
exitRoom to exit the current room:trtcCloud.stopLocalPreview();trtcCloud.stopLocalAudio();trtcCloud.exitRoom();
onExitRoom callback registered in Step 3. In this callback, you can unregister the listener and destroy the instance:void releaseTRTC() {trtcCloud.unRegisterListener(listener);TRTCCloud.destroySharedInstance();}
exitRoom is asynchronous. The SDK triggers onExitRoom after it releases device resources such as the camera and microphone. To enter a room again, call enterRoom after receiving onExitRoom. Otherwise, issues such as devices being occupied may occur.userId values on two devices to enter the same room.import 'dart:io';import 'package:flutter/material.dart';import 'package:permission_handler/permission_handler.dart';import 'package:tencent_rtc_sdk/trtc_cloud.dart';import 'package:tencent_rtc_sdk/trtc_cloud_def.dart';import 'package:tencent_rtc_sdk/trtc_cloud_listener.dart';import 'package:tencent_rtc_sdk/trtc_cloud_video_view.dart';const int sdkAppId = 0; // Replace with your SDKAppIDconst String userId = 'user_a'; // Replace with your userIdconst String userSig = ''; // Replace with the UserSig corresponding to this userIdconst String roomId = '123abc'; // Replace with your room IDvoid main() => runApp(const MaterialApp(home: VideoCallPage()));class VideoCallPage extends StatefulWidget {const VideoCallPage({super.key});@overrideState<VideoCallPage> createState() => _VideoCallPageState();}class _VideoCallPageState extends State<VideoCallPage> {TRTCCloud? trtcCloud;late final TRTCCloudListener listener;final List<String> remoteUsers = [];@overridevoid initState() {super.initState();listener = TRTCCloudListener(onError: (errCode, errMsg) => debugPrint('onError: $errCode, $errMsg'),onEnterRoom: (result) =>debugPrint(result > 0 ? 'Entered room successfully' : 'Failed to enter room: $result'),onUserVideoAvailable: onRemoteVideoChanged,onExitRoom: (reason) {trtcCloud?.unRegisterListener(listener);TRTCCloud.destroySharedInstance();},);start();}Future<void> start() async {if (!await requestPermissions()) {debugPrint('Camera or microphone permission not granted');return;}final cloud = await TRTCCloud.sharedInstance();cloud.registerListener(listener);cloud.enterRoom(TRTCParams(sdkAppId: sdkAppId,userId: userId,userSig: userSig,strRoomId: roomId,),TRTCAppScene.videoCall,);cloud.startLocalAudio(TRTCAudioQuality.defaultMode);if (mounted) setState(() => trtcCloud = cloud);}Future<bool> requestPermissions() async {if (!(Platform.isAndroid || TRTCPlatform.isOhos)) return true;final statuses = await [Permission.camera, Permission.microphone].request();return statuses.values.every((status) => status.isGranted);}void onRemoteVideoChanged(String uid, bool available) {if (!mounted) return;setState(() {if (available) {if (!remoteUsers.contains(uid)) remoteUsers.add(uid);} else {remoteUsers.remove(uid);trtcCloud?.stopRemoteView(uid, TRTCVideoStreamType.big);}});}@overridevoid dispose() {trtcCloud?.stopLocalPreview();trtcCloud?.stopLocalAudio();trtcCloud?.exitRoom();super.dispose();}@overrideWidget build(BuildContext context) {final cloud = trtcCloud;return Scaffold(appBar: AppBar(title: const Text('Room: $roomId')),body: cloud == null? const Center(child: CircularProgressIndicator()): GridView.count(crossAxisCount: 2,children: [TRTCCloudVideoView(key: const ValueKey('local'),onViewCreated: (viewId) =>cloud.startLocalPreview(true, viewId),),for (final uid in remoteUsers)TRTCCloudVideoView(key: ValueKey('remote_$uid'),onViewCreated: (viewId) => cloud.startRemoteView(uid, TRTCVideoStreamType.big, viewId),),],),floatingActionButton: FloatingActionButton(backgroundColor: Colors.red,onPressed: () => Navigator.of(context).maybePop(),child: const Icon(Icons.call_end),),);}}
피드백