Integration
This tutorial mainly introduces how to implement a basic audio and video call.
Prerequisites
Android Studio 3.5 or later.
Android 4.1 (SDK API level 16) or later
Step 1. Import TRTC SDK
1. Add TRTC SDK dependencies to the
app/build.gradle
file.dependencies {implementation 'com.tencent.liteav:LiteAVSDK_TRTC:latest.release'}
2. Specify the CPU architecture used by the App in the
defaultConfig
file.defaultConfig {ndk {abiFilters "armeabi-v7a", "arm64-v8a"}}
Once the above configuration completed, clicking
Sync Now
will automatically integrate the SDK into the target project.Step 2. Configure project
1. Configure the permissions required by the TRTC SDK in the
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.BLUETOOTH" /><uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera.autofocus" />
Note:
Do not set the
android: hardwareAccelerated = "false"
. When hardware acceleration is turned off, the other party's video stream cannot be rendered.2. In the
proguard-rules.pro
file, add the TRTC SDK-related classes to the "non-obfuscation" list.-keep class com.tencent.** { *; }
Step 3. Create TRTC instance
1. Declare member variables
private final static String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_CAMERA_AND_MICROPHONE = 1;private TRTCCloud mCloud; // Declare the mCloud member variable
2. Call the initialization interface to create the TRTC instance and set the event callbacks.
// Create trtc instance(singleton) and set up event listenersmCloud = TRTCCloud.sharedInstance(getApplicationContext()); mCloud.setListener(new TRTCCloudListener() {// Listen to the "onError" event, and print logs for errors such as "Camera is not authorized" @Override public void onError(int errCode, String errMsg, Bundle extraInfo) { super.onError(errCode, errMsg, extraInfo); if (errCode == TXLiteAVCode.ERR_CAMERA_NOT_AUTHORIZED) { Log.d(TAG, "Current application is not authorized to use the camera"); } }// Listen for the `onEnterRoom` event of the SDK and learn whether the room is successfully entered @Override public void onEnterRoom(long result) { super.onEnterRoom(result); if (result > 0) { Log.d(TAG, "Enter room succeed"); } else { Log.d(TAG, "Enter room failed"); } } });
Step 4. Enter the room
1. Request CAMERA and MICROPHONE permissions.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);// ... Other codes// Request camera and microphone permissions requestCameraAndMicrophonePermission(); } private void requestCameraAndMicrophonePermission() { String[] permissions = {android.Manifest.permission.CAMERA, android.Manifest.permission.RECORD_AUDIO}; ActivityCompat.requestPermissions(this, permissions, REQUEST_CAMERA_AND_MICROPHONE); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CAMERA_AND_MICROPHONE) { boolean allPermissionsGranted = true; for (int grantResult : grantResults) { if (grantResult != PackageManager.PERMISSION_GRANTED) { allPermissionsGranted = false; break; } } if (allPermissionsGranted) { // All permissions are granted, you can start using the camera and microphone// Here to create TRTC instances, enter the room, publish audio and video streams, subscribe audio and video streams and check out and other functions } else { // Show a message to the user that the permissions are required to use the app features Toast.makeText(this, "Camera and Microphone permissions are required", Toast.LENGTH_SHORT).show(); } } }
2. Click
Create Application
in the Tencent RTC console to get the SDKAppID under Application Overview tab.
3. Select SDKAppID down in the UserSig Tools, enter your UserID, and click
Generate
to get your own UserSig.
4. After setting the TRTCParams for room entry, call the
enterRoom
to enter the room. As an Anchor:
// Please replace each field in TRTCParams with your own parametersTRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();trtcParams.sdkAppId = 1400000123; // Please replace with your own SDKAppIDtrtcParams.userId = "denny"; // Please replace with your own useridtrtcParams.roomId = 123321; // Please replace with your own room numbertrtcParams.userSig = "xxx"; // Please replace with your own userSigtrtcParams.role = TRTCCloudDef.TRTCRoleAnchor;// If your application scenario is a video call between several people, please use "TRTC_APP_SCENE_LIVE"mCloud.enterRoom(trtcParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
As an audience:
// Please replace each field in TRTCParams with your own parametersTRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();trtcParams.sdkAppId = 1400000123; // Please replace with your own SDKAppIDtrtcParams.userId = "denny"; // Please replace with your own useridtrtcParams.roomId = 123321; // Please replace with your own room numbertrtcParams.userSig = "xxx"; // Please replace with your own userSigtrtcParams.role = TRTCCloudDef.TRTCRoleAudience;// If your application scenario is a video call between several people, please use "TRTC_APP_SCENE_LIVE"mCloud.enterRoom(trtcParams, TRTCCloudDef.TRTC_APP_SCENE_LIVE);
Note:
If you enter the room as an audience, sdkAppId and roomId need to be the same as on the anchor side, while userId and userSig need to be replaced with your own values.
Step 5. Turn on Camera
1. Add in the corresponding .xml file, as shown in the following code.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <com.tencent.rtmp.ui.TXCloudVideoView android:id="@+id/txcvv_main_local" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
2. Before calling the
startLocalPreview
to open the camera preview, set the TRTCRenderParams of the local preview by calling the setLocalRenderParams
.// Set the preview mode of the local screenTRTCCloudDef.TRTCRenderParams trtcRenderParams = new TRTCCloudDef.TRTCRenderParams();trtcRenderParams.fillMode = TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;trtcRenderParams.mirrorType = TRTCCloudDef.TRTC_VIDEO_MIRROR_TYPE_AUTO;mCloud.setLocalRenderParams(trtcRenderParams);// Start a preview of the local cameraTXCloudVideoView cameraVideo = findViewById(R.id.txcvv_main_local);mCloud.startLocalPreview(true, cameraVideo);
3. Call the
TXDeviceManager
to perform operations such as Switching between front and rear cameras, Setting Focus Mode, and Enabling.// Enable auto focus and turn on the flash using the TXDeviceManagerTXDeviceManager manager = mCloud.getDeviceManager();if (manager.isAutoFocusEnabled()) {manager.enableCameraAutoFocus(true);}manager.enableCameraTorch(true);
Note:
The front camera is turned on by default. If you need to use the rear camera, call
manager.switchCamera(false)
to turn on the rear camera.Step 6. Turn on microphone
Call
startLocalAudio
to enable microphone capture. This interface requires you to determine the capture mode by the quality
parameter. It is recommended to select one of the following modes that is suitable for your project according to your needs.// Enable microphone acquisition and set the current scene to: Voice mode// For high noise suppression capability, strong and weak network resistancemCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH );// Enable microphone acquisition, and set the current scene to: Music mode (// For high fidelity acquisition, low sound quality loss, recommended to use with professional sound cardsmCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_MUSIC);
Step 7. Play/stop video streaming
After you enter denny's room as an audience by following steps 1-4 to create a new project, you can play a video of the remote user by calling the
startRemoteView
.// Play denny's camera footagemCloud.startRemoteView("denny", TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,cameraView);
Then, you can call the
stopRemoteView
to stop the videos of a remote user. Alternatively, you can also stop the videos of all remote users via the stopAllRemoteView
.// Stop denny's camera footagemCloud.stopRemoteView("denny", TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,cameraView);// Stop all camera footagesmCloud.stopAllRemoteView();
Step 8. Play/stop the audio stream
Mute the voice of remote user denny by calling the
muteRemoteAudio("denny", true)
.// Mute user with id dennymCloud.muteRemoteAudio("denny", true);
You can also unmute him later by calling the
muteRemoteAudio("denny", false)
.// Unmute user with id dennymCloud.muteRemoteAudio("denny", false);
Step 9. Exit the room
Call the
exitRoom
to exit the current room, the SDK will notify you after the check-out through the onExitRoom(int reason)
callback event.// Exit current roommCloud.exitRoom();// Listen for the `onExitRoom` callback to get the reason for room exit@Overridepublic void onExitRoom(int reason) {if (reason == 0) {Log.d(TAG, "Exit current room by calling the 'exitRoom' api of sdk ...");} else if (reason == 1) {Log.d(TAG, "Kicked out of the current room by server through the restful api...");} else if (reason == 2) {Log.d(TAG, "Current room is dissolved by server through the restful api...");}}
FAQs
Contact us
If you have any suggestions or feedback, please contact
info_rtc@tencent.com
.