uni-app (uts plugin)

更新时间:
复制 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

Procedure

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

For a demo, see the UniApp directory at: https://github.com/aliyun/AliRTCSample/tree/master/UniApp

  1. Initialize the SDK.

    Create an IUDingRtcEngine instance and register callbacks.

    <script setup lang="uts">
        import { APP_ID, TOKEN, GSLB_SERVER, USER_NAME } from "@/store/index.uts"
        import { IUDingRtcEngine,
    	     UDingRtcEventListener,
    	     createRtcEngine } from "@/uni_modules/Dingtalk-DingRTC"
        let engine : IUDingRtcEngine | null = null
        
        ...
    </script>
    function createDingRtcEngine() {
            engine = createRtcEngine({
                onJoinChannelResult: (result: Number, channel: String, userId: String, elapsed: Number) => {
                    console.log(`onJoinChannelResult result = ${result}`)
                    if (result == 0) {
                        uni.showToast({
                            title: `Joined the channel. Time elapsed: ${elapsed}ms`,
                            icon: 'none',
                        })
                    } else {
                        console.log(`join channel failed,error code = ${result}`);
                    }
                },
                onLeaveChannelResult: (result: Number) => {
                    console.log(`onLeaveChannelResult result = ${result}`)
                    uni.showToast({
                        title: `Left the channel: ${result}`,
                        icon: 'none',
                    })
                },
                onRemoteUserOnLineNotify: (userId: String, elapsed: Number) => {
                    console.log(`remote user join channel,uid = ${userId}`)
                    remoteUserId.value = userId
                    uni.showToast({
                        title: `Remote user joined: ${userId}`,
                        icon: 'none',
                    })
                },
                onRemoteUserOffLineNotify: (userId: String, reason: UDingRtcUserOfflineReason) => {
                    console.log(`remote user leave channel,uid = ${userId}`)
                    uni.showToast({
                        title: `Remote user left: ${userId}, reason: ${reason}`,
                        icon: 'none',
                    })
                },
                onOccurError: (error: Number, msg: String) => {
                    console.log(`occur error ${error}, msg = ${msg}`)
                    uni.showToast({
                        title: `SDK error: ${error}`,
                        icon: 'none',
                    })
                }
            } as UDingRtcEventListener)
        }
    1. Preview the local video. After you create the IUDingRtcEngine instance, you need to create an RtcSurfaceView layout to preview the local video.

      <template>
      ...
      <view>
          <RtcSurfaceView :id="userId" style="height: 403.84rpx;flex: 1;"></RtcSurfaceView>
      </view>
      ...
      </template>
      import { UDingRtcVideoCanvas } from "@/uni_modules/Dingtalk-DingRTC"
      		
      function startLocalPreview() {
              // 1. Bind the view.
              engine?.setLocalViewConfig({
                  viewId: userId,
                  renderMode: 2,
                  mirrorMode: 0,
                  backgroundColor: 0xffffff,
                  rotationMode: 0,
              } as UDingRtcVideoCanvas, 1)
              // 2. Start the local preview.
              engine?.startPreview()
          }
      Note
      • UDingRtcRenderMode provides four rendering modes:

        • 0: auto, automatic mode.

        • 1: stretch, stretch-to-fill mode. If the aspect ratio of the input video does not match the aspect ratio set for stream ingest, the video is stretched to fit, which distorts the image.

        • 2: fill, fit-with-black-bars mode. If the aspect ratio of the input video does not match the aspect ratio set for stream ingest, black bars are added to the top and bottom or to the sides of the video.

        • 3: crop, crop-to-fill mode. If the aspect ratio of the input video does not match the aspect ratio set for stream ingest, the video is cropped by width or height, which results in content loss.

      • You can set the mirror mode for local or remote views using UDingRtcRenderMirrorMode. This parameter provides three mirror modes:

        • 0: onlyFrontCameraPreviewEnabled, mirrors the preview of the front camera only. Other views are not mirrored.

        • 1: allEnabled, enables mirroring for all views.

        • 2: allDisabled, disables mirroring for all views.

    2. Optional: Stop the local preview.

      engine?.stopPreview() 
    3. Configure publishing and subscription.

      • By default, the SDK does not automatically publish audio and video streams after a user joins a channel. To enable automatic publishing, call the following methods before the user joins the channel:

        engine?.publishLocalAudioStream(true)// Publish the audio stream by default.
        engine?.publishLocalVideoStream(true)// Publish the video stream by default.
      • By default, the SDK automatically subscribes to remote audio and video streams after a user joins a channel. To disable automatic subscription, call the following methods before the user joins the channel:

        engine?.subscribeAllRemoteAudioStreams(false)// Do not subscribe to audio streams.
        engine?.subscribeAllRemoteVideoStreams(false)// Do not subscribe to video streams.
  2. Join a channel.

    import { UDingRtcAuthInfo } from "@/uni_modules/Dingtalk-DingRTC"
    
    function joinChannel() {
            let ret = engine?.joinChannel({
                channelId: channelId, // Your channel ID
                userId: userId, // Your user ID
                appId: APP_ID, // Your app ID
                token: TOKEN, // Your token
                gslbServer: GSLB_SERVER // Your GSLB endpoint
            } as UDingRtcAuthInfo, USER_NAME)
            if (ret != 0) {
                console.log(`joinChannel error = ${ret}`)
            } else {
                uni.showToast({
                    title: 'joinChannel ',
                    icon: 'none',
                });
            }
        }

    The result of joining the channel is returned in the onJoinChannelResult callback.

    Parameter

    Description

    appId

    The app ID. Create and view the app ID on the Application Management page in the console.

    channelId

    The channel ID. The ID must be 1 to 64 characters in length and can contain uppercase letters, lowercase letters, digits, underscores (_), and hyphens (-).

    userId

    The user ID. The ID must be 1 to 64 characters in length and can contain uppercase letters, lowercase letters, digits, underscores (_), and hyphens (-).

    Note

    If the same user ID logs on from another client, the client that joined the channel first is removed from the channel by the client that joined later.

    token

    The token for channel authentication.

    gslbServer

    The service endpoint. This parameter can be empty. The default value is "https://gslb.dingrtc.com". Send this endpoint from your business server to the client SDK. Do not hardcode the endpoint in your client code.

    Important: Do not pass an empty value. Use the GSLB endpoint returned from your business server (AppServer).

  3. Publish or unpublish local streams.

    • Publish local audio and video streams

      If you did not configure automatic publishing before a user joins a channel, you can call the following methods to manually publish the local streams:

      engine?.publishLocalAudioStream(true)// Publish the audio stream.
      engine?.publishLocalVideoStream(true)// Publish the video stream.
    • Unpublish local audio and video streams

      To unpublish the local audio and video streams, 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

      By default, the SDK automatically subscribes to remote streams after a user joins a channel. If you disabled automatic subscription before the user joined, you can call the following methods to subscribe manually:

      engine?.subscribeAllRemoteAudioStreams(true)// Subscribe to all remote audio streams.
      engine?.subscribeAllRemoteVideoStreams(true)// Subscribe to all remote video streams.
    • Before you render the remote video, create an RtcSurfaceView layout.

      <template>
      ...
      <view>
          <RtcSurfaceView v-if="remoteUserId" :id="remoteUserId" style="height: 403.84rpx;flex: 1">
          </RtcSurfaceView>
      </view>
      ...
      </template>
    • After a successful subscription, render the remote video when you receive the onRemoteTrackAvailableNotify callback:

      function startRemoteView() {
              console.log(`startRemoteView, user = ${remoteUserId.value}`)
              engine?.setRemoteViewConfig({
                  viewId: remoteUserId.value,
      	    renderMode: 2,
      	    mirrorMode: 0,
                  backgroundColor: 0xffffff,
      	    rotationMode: 0,
              } as UDingRtcVideoCanvas, remoteUserId.value, 1)
          } 
    • Unsubscribe from remote audio and video streams

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

      engine?.subscribeAllRemoteAudioStreams(false)// Unsubscribe from all remote audio streams.
      engine?.subscribeAllRemoteVideoStreams(false)// Unsubscribe from all remote video streams.
    • Subscribe to the audio and video streams of a specific user

      After you unsubscribe from all streams, you can call the following method to subscribe to the streams of a specific remote user:

      engine?.subscribeRemoteVideoStream(remoteUserId.value, 1, true)// Subscribe to the video stream of a specific user.
  5. Leave the channel.

    engine?.leaveChannel()