WeChat Mini Program SDK

更新时间:
复制 MD 格式

This topic describes how to integrate ApsaraVideo Real-time Communication into a WeChat mini program.

Prerequisites

  • The minimum required version of the mini program base library is 2.10.0.

  • The minimum required version of the WeChat app is 7.0.9.

  • Your mini program has permission to use the live-pusher and live-player components. For information about the requirements and the procedure to enable these permissions, see the WeChat live-pusher documentation.

Note

WeChat DevTools does not support the live-pusher and live-player components. Use a physical device for development and testing. Test accounts for mini programs cannot be used for testing.

Step 1: Create an application

  1. Log on to the ApsaraVideo Live console.

  2. In the navigation pane on the left, click Live + > ApsaraVideo Real-time Communication > Applications.

  3. Click Create Application.

  4. Enter a custom instance name, select the Terms of Service checkbox, and then click Buy Now.

  5. After a success message is displayed, you can refresh the Application Management page to view your new ApsaraVideo Real-time Communication application.

    Note

    By default, creating an application does not incur charges. You are charged based on your actual usage. For more information, see Audio and Video Call Fees.

Step 2: Get your Application ID and AppKey

After you create the application, find it in the application list. In the Actions column, click Manage to go to the Basic Information page. On this page, you can find the Application ID and AppKey.

image

Step 3: Integrate the SDK

  1. On the WeChat Official Accounts Platform, navigate to Management > Development Management > Server Domain Names. Set the valid domain names for request and socket as follows:

    Valid domain names for request
    https://alivc-aio.cn-hangzhou.log.aliyuncs.com
    https://apsara-video-client.cn-shanghai.log.aliyuncs.com
    https://gw.rtn.aliyuncs.com
    https://slsrole.alicdn.com
    Valid domain names for socket
    wss://rs.rtn.aliyuncs.com
  2. In your mini program's JS file, define data for live-pusher and live-player.

    Component({
      data: {
        pusher: {},
        playerList: [],
      },
    });
  3. In your mini program's WXML file, bind the data to live-pusher and live-player.

    <live-pusher
      url="{{pusher.url}}"
      beauty="{{pusher.beauty}}"
      whiteness="{{pusher.whiteness}}"
      mode="{{pusher.mode}}"
      autopush="{{pusher.autopush}}"
      mirror="{{pusher.mirror}}"
      local-mirror="{{pusher.localMirror}}"
      remote-mirror="{{pusher.remoteMirror}}"
      enable-ans="{{pusher.enableAns}}"
      enable-agc="{{pusher.enableAgc}}"
      device-position="{{pusher.devicePosition}}"
      muted="{{!pusher.enableMic}}"
      enable-mic="{{pusher.enableMic}}"
      enable-camera="{{pusher.enableCamera}}"
      bindstatechange="onPusherStateChange"
      bindnetstatus="onPusherNetStatus"
      binderror="onPusherError"
      <!-- Other properties are omitted. For more information about the properties, see the live-pusher documentation. -->
    />
    <view class="player-container" wx:for="{{playerList}}" wx:key="id">
      <live-player
        id="{{item.id}}"
        src="{{item.src}}"
        mode="{{item.mode}}"
        autoplay="{{item.autoplay}}"
        muted="{{item.muted}}"
        mute-audio="{{item.muteAudio}}"
        mute-video="{{item.muteVideo}}"
        min-cache="{{item.minCache}}"
        max-cache="{{item.maxCache}}"
        bindstatechange="onPlayerStateChange"
        bindnetstatus="onPlayerNetStatus"
        <!-- Other properties are omitted. For more information about the properties, see the live-player documentation. -->
      />
    </view>
  4. Use npm to integrate the SDK.

    npm install aliyun-rtc-wx-sdk
  5. Initialize the engine.

    import AliRtcEngine from "aliyun-rtc-wx-sdk";
    
    this.artc = AliRtcEngine.getInstance(this)
  6. After you create the AliRtcEngine instance, listen for and handle related events.

    this.artc.on("remoteUserOnLineNotify", (user, playerList) => {
      wx.showToast({
        title: `${user.displayName || user.userId} joined the channel`,
        icon: "none",
      });
      this.setData({
        playerList,
      });
    });
    this.artc.on("remoteUserOffLineNotify", (user, playerList) => {
      wx.showToast({
        title: `${user.displayName || user.userId} left the channel`,
        icon: "none",
      });
      this.setData({
        playerList,
      });
    });
    this.artc.on("remoteTrackAvailableNotify", (user, playerList) => {
      this.setData({
        playerList,
      });
    });
    this.artc.on("bye", () => {
      wx.showToast({
        title: "You have been kicked out of the channel",
        icon: "none",
      });
      this.setData({
        pusher: {},
        playerList: [],
      });
    });
  7. Join a channel. You can join a channel with a single parameter or multiple parameters as needed. For information about how to calculate a token, see Token-based authentication.

    • Join a channel with a single parameter:

      const userName = 'TestUser1'; // You can change this to your username. Chinese characters are supported.
      
      try {
        // You must implement fetchToken to obtain the Base64 token from the server.
        const base64Token = await fetchToken();
        const { pusherAttributes, playerList } = await this.artc.joinChannel(base64Token, userName);
        // Joined the channel. You can perform other operations.
      } catch (error) {
        // Failed to join the channel.
      }
    • Join a channel with multiple parameters:

      // For more information, see the Token-based authentication topic. Generate authentication information from the server or locally.
      // Note: For data security, do not release the token calculation logic that contains the AppKey to users.
      const appId = 'yourAppId'; // Obtain this from the console.
      const appKey = 'yourAppKey'; // Obtain this from the console. Do not expose your AppKey in a production environment.
      const channelId = 'AliRtcDemo'; // You can change this to your channel ID. Only letters and digits are supported.
      const userId = 'test1'; // You can change this to your user ID. Only letters and digits are supported.
      const userName = 'TestUser1'; // You can change this to your username. Chinese characters are supported.
      const timestamp = Math.floor(Date.now() / 1000) + 3600; // Expires in one hour.
      
      try {
        const token = await generateToken(appId, appKey, channelId, userId, timestamp);
        // Join the channel. Parameters such as token and nonce are typically returned by the server.
        const { pusherAttributes, playerList } = await this.artc.joinChannel({
          channelId,
          userId,
          appId,
          token,
          timestamp,
        }, userName);
        // Joined the channel. You can perform other operations.
      } catch (error) {
        // Failed to join the channel.
      }
  8. After you join the channel, update data and start stream ingest.

    this.setData(
      {
        pusher: pusherAttributes,
        playerList,
      },
      () => {
        this.artc.getPusherInstance().start();
      },
    );
  9. In the methods object, define the event handling methods for live-pusher and live-player.

    Component({
      methods: {
        onPusherStateChange(e: any) {
          // For information about the code for live-pusher, see the live-pusher documentation.
          console.log("live-pusher code: ", e.detail.code);
          this.artc.handlePusherStateChange(e);
        },
        onPusherNetStatus(e: any) {
          console.log("live-pusher netStatus: ", e.detail.info);
          this.artc.handlePusherNetStatus(e);
        },
        onPusherError(e: any) {
          this.artc.handlePusherError(e);
        },
        onPlayerStateChange(e: any) {
          // For information about the code for live-player, see the live-player documentation.
          console.log("live-player code: ", e.detail.code);
          this.artc.handlePlayerStateChange(e);
        },
        onPlayerNetStatus(e: any) {
          console.log("live-player netStatus: ", e.detail.info);
          this.artc.handlePlayerNetStatus(e);
        },
      },
    });
  10. Leave the meeting.

    await this.artc.leaveChannel();
    this.setData({
      pusher: {},
      playerList: [],
    });