Android

更新时间:
复制 MD 格式

The basic features of ApsaraVideo Real-time Communication (RTC) include initializing the software development kit (SDK), joining a channel, publishing local streams, subscribing to remote streams, and leaving a channel. This topic describes how to implement these basic features.

Prerequisites

Limits

This topic applies only to SDK 2.1 and later. If you need the documentation for SDK 1.17, see Implement basic features on Android.

Procedure

Note The implementation methods in this topic are for reference only. You must develop your application based on your specific requirements.
  1. Initialize the SDK.

    Create an AliRtcEngine instance and register callbacks. For more information about the callback interfaces, see Callbacks and listeners.

    private void getInstance() {
    
      AliRtcEngine engine = AliRtcEngine.getInstance(getApplicationContext());
      engine.setRtcEngineEventListener(eventListener);
      engine.setRtcEngineNotify(engineNotify); 
    }
    1. Preview the local video. After you create the AliRtcEngine instance, you can create a canvas layout to preview the local video.
      private void setLocalViewConfig() {
      
          // Create a SurfaceView object.
          private FrameLayout mLocalContainer;
          private SurfaceView mLocalView;
      
          mLocalView = engine.CreateRendererView(getApplicationContext());
          mLocalView.setZOrderMediaOverlay(true);
          mLocalContainer.addView(mLocalView);
          // Set the local view.
          AliVideoCanvas canvas = new AliRtcEngine.AliVideoCanvas();
        canvas.view = surfaceView; 
        canvas.renderMode = AliRtcRenderModeAuto;    
          engine.setLocalViewConfig(canvas,AliRtcVideoTrackCamera);
          engine.startPreview();
      }
      Note
      • The `AliRtcRenderMode` class provides four rendering modes:
        • AliRtcRenderModeAuto (Recommended): The video is rendered automatically.
        • AliRtcRenderModeStretch: The video is stretched to fill the view without preserving the aspect ratio.
        • AliRtcRenderModeFill: The video is scaled to fill the view while preserving the aspect ratio. Black bars may be added.
        • AliRtcRenderModeClip: The video is scaled and clipped to fit the view while preserving the aspect ratio.
      • You can set the mirror mode for the local or remote view using `AliRtcRenderMirrorMode`. Three mirror modes are available:
        • AliRtcRenderMirrorModeOnlyFront: Only the preview of the front camera is mirrored.
        • AliRtcRenderMirrorModeAllEnabled: All views are mirrored.
        • AliRtcRenderMirrorModeAllDisable: No views are mirrored.
    2. Optional:Stop the local preview.
      engine.stopPreview();
    3. Configure publishing and subscribing.
      • By default, the SDK automatically publishes audio and video streams after a user joins a channel. If you do not want to automatically publish the streams, you can call the following methods before the user joins the channel:
        engine.publishLocalAudioStream(false);// Do not publish the audio stream by default.
        engine.publishLocalVideoStream(false);// Do not publish the video stream by default.
      • By default, the SDK automatically subscribes to remote audio and video streams after a user joins a channel. If you do not want to automatically subscribe to the streams, you can call the following methods before the user joins the channel:
        engine.setDefaultSubscribeAllRemoteAudioStreams(false);// Do not subscribe to audio streams by default.
        engine.setDefaultSubscribeAllRemoteVideoStreams(false);// Do not subscribe to video streams by default.
  2. Join a channel.
    AliRtcAuthInfo userInfo = new AliRtcAuthInfo();
    authinfo.channelId   = /* Your channelId */;
    authinfo.appId     = /* Your AppId */;
    authinfo.nonce     = /* Your nonce */;
    authinfo.userId   = /* Your userId */;
    authinfo.token     = /* Your token */;
    authinfo.timestamp = /* Your timestamp */;
    authinfo.gslb      = /* Your GSLB endpoint */;
    
    engine.joinChannel(userInfo, mUsername);
    ParameterDescription
    appIdThe application ID. You can create and view the application ID on the Application Management page in the console.
    channelIdThe channel ID. It can be 1 to 64 characters in length and can contain letters, digits, underscores (_), and hyphens (-).
    userIdThe user ID. It can be 1 to 64 characters in length and can contain letters, digits, underscores (_), and hyphens (-).
    Note If a user joins a channel with a user ID that is already used in the channel, the original user with that ID is removed from the channel.
    nonceA random code. It must start with the `AK-` prefix and can contain letters and digits. The maximum length is 64 bytes. Example: `AK-2b9be4b25c2d38c409c376ffd2372be1`.
    timestampThe timestamp that indicates when the token expires. You can set the validity period to 12 hours, 24 hours, 3 days, or 7 days.
    tokenThe token for channel authentication. It is calculated using the following formula: token = sha256(appId + appKey + channelId + userId + nonce + timestamp).
    gslbThe service endpoint. This parameter is an array. Use ["https://rgslb.rtc.aliyuncs.com"]. We recommend that you obtain the endpoint from your business server and pass it to the client SDK. Do not hardcode the endpoint in your client code.
  3. Publish or unpublish local streams.
    • Publish local audio and video streams

      If you did not configure the publishing settings before joining the channel, the local audio and video streams are automatically published after you join the channel. If you disabled automatic publishing before joining the channel, you can call the following methods to manually publish the streams:

      engine.publishLocalAudioStream(true);// Publish the audio stream.
      engine.publishLocalVideoStream(true);// Publish the video stream.
    • Publish a low-resolution stream

      By default, the SDK does not publish a low-resolution stream. To publish a low-resolution stream, you can call the following method. You can call this method before or after you join a channel.

      engine.publishLocalDualStream(true);
    • Unpublish local audio and video streams

      To unpublish the local audio and video streams, you can call the following methods:

      engine.publishLocalAudioStream(false);//Unpublish the audio stream
      engine.publishLocalVideoStream(false);//Unpublish the video stream
  4. Subscribe to or unsubscribe from remote streams.
    • Subscribe to remote audio and video streams

      If you did not configure the subscription settings before joining the channel, the remote audio and video streams are automatically subscribed to after you join the channel. If you disabled automatic subscription before joining the channel, you can call the following methods to manually subscribe to the streams:

      engine.setDefaultSubscribeAllRemoteAudioStreams(true);// Subscribe to all remote audio streams.
      engine.setDefaultSubscribeAllRemoteVideoStreams(true);// Subscribe to all remote video streams.
      Note These methods apply only to remote users who join the channel after the methods are called. They do not affect remote users who are already in the channel.

      After you subscribe to the streams, you can render the remote video in the `onRemoteTrackAvailableNotify` callback:

       public void onRemoteTrackAvailableNotify(String uid, AliRtcEngine.AliRtcAudioTrack audioTrack,
                                                       AliRtcEngine.AliRtcVideoTrack videoTrack) {
              // Handle the UI or logic. For example, render the remote video stream.
              if(videoTrack == AliRtcVideoTrackCamera) {
              // Video stream.
              AliRtcEngine.AliRtcVideoCanvas canvas = new AliRtcEngine.AliRtcVideoCanvas();
              canvas.renderMode = /* renderMode */;
              canvas.view = view;/* The rendering view */
              engine.setRemoteViewConfig(canvas, uid, AliRtcVideoTrackCamera);
            }
          });
      } 
    • Unsubscribe from remote audio and video streams

      To unsubscribe from remote audio and video streams, you can call the following methods:

      engine.setDefaultSubscribeAllRemoteAudioStreams(false);// Unsubscribe from remote audio streams.
      engine.setDefaultSubscribeAllRemoteVideoStreams:(false);// Unsubscribe from remote video streams.
      Note These methods apply only to remote users who join the channel after the methods are called. They do not affect remote users who are already in the channel.
    • Subscribe to the audio and video streams of a specific user

      After you unsubscribe from all audio and video streams, you can call the following methods to subscribe to the streams of a specific remote user. To unsubscribe from the streams of the user, you can set the `sub` parameter to `false`.

      engine.subscribeRemoteAudioStream(uid,true);// Subscribe to the audio stream of a specific user.
      engine.subscribeRemoteVideoStream(uid,AliRtcVideoTrackCamera,true);// Subscribe to the video stream of a specific user.
    • Subscribe to a low-resolution stream

      To subscribe to a low-resolution stream, you can call the following method:

      engine.setRemoteDefaultVideoStreamType(AliRtcVideoStreamTypeLow);
      Note These methods apply only to remote users who join the channel after the methods are called. They do not affect remote users who are already in the channel.
    • Unsubscribe from the audio and video streams of all remote users

      To unsubscribe from the streams of all current and subsequent users in the channel, you can call the following methods:

      engine.subscribeAllRemoteAudioStreams(false);
      engine.subscribeAllRemoteVideoStreams(false);
      Note
      • If you set the parameters in these methods to `false`, these settings take the highest priority. The `setDefaultSubscribeAllRemoteAudioStreams` and `setDefaultSubscribeAllRemoteVideoStreams` methods do not take effect, even if their parameters are set to `true`.
      • If you set the parameters in these methods to `true`, the subscription settings are determined by the `setDefaultSubscribeAllRemoteAudioStreams` and `setDefaultSubscribeAllRemoteVideoStreams` methods.
  5. Leave the channel.
    engine.leaveChannel(); 

What to do next

You can download the sample code and run the demo to start a real-time audio and video call with other users in a channel. For more information, see Run the Android demo.