Advanced usage

更新时间:
复制 MD 格式

This topic describes advanced usage of the Web RTS Push software development kit (SDK).

Browser compatibility check

You can check whether the current browser environment supports stream ingest and capture.

Note

This is a static method. You can call it directly on AliRTSPusher without creating an instance.

const checkResult = await AliRTSPusher.checkSupport();
console.log('checkResult: ', checkResult);

For more information about the check result, see ISupportResult.

Device management

You can retrieve the lists of microphones and cameras that are available to the current browser.

// Get the camera list
const cameraList = await deviceManager.getCameraList();
// Get the microphone list
const micList = await deviceManager.getMicList();

For more information, see the DeviceManager API.

Monitor stream ingest status

You can listen to the connectStatusChange event to monitor the network status of the stream ingest. This lets you provide prompts to users and retry the operation if needed.

pushClient.on('connectStatusChange', (event) => {
  switch (event.status) {
    case 1:
      // Connecting
      break;
    case 2:
      // Connected
      break;
    case 3:
      // Reconnecting automatically. Note that stream ingest is temporarily interrupted. Prompt the user right away.
      break;
    case 0:
      // Disconnected. Stream ingest has ended. Prompt the user. If needed, call startPush again to start stream ingest.
      break;
  }
})

For more information, see the EConnectStatus status enumeration.

Set the stream ingest bitrate in stream mixing mode

Currently, the setMixingConfig method does not support setting the maximum bitrate in stream mixing mode. You can set the maximum bitrate as follows:

/**
 * Sets the bitrate and sending frame rate. Call this after stream ingest starts successfully.
 * @param pushClient The current Push SDK instance.
 * @param config The bitrate and frame rate settings.
 * @param config.maxBitrate The maximum bitrate in kbps.
 * @param config.maxFramerate The maximum frame rate.
 *
 *
 * @example
 * ```ts
 * setSenderParams(aliPusher, { maxBitrate: 3000, maxFramerate: 20 })
 * ```
 */

function setSenderParams(pushClient, config) {
  const pcm = pushClient.publisher?.peerconnection;
  if (pcm) {
    pcm.setVideoSenderParams(config);
  }
}

How do I switch cameras during stream ingest?

To switch between cameras during stream ingest, such as from camera A to camera B, follow these steps:

Non-stream mixing mode

  1. Retrieve the list of active cameras:

    const deviceManager = pushClient.getDeviceManager();
    // cameraList contains the deviceId for each camera
    const cameraList = await deviceManager.getCameraList();
  2. Switch to the target camera using startCamera:

    // If you are ingesting a stream from camera A and need to switch to camera B
    await pushClient.startCamera(deviceId); // Pass the deviceId of camera B

Stream mixing mode

In stream mixing mode, each camera and screen sharing feed is shared or played through a layer. To switch cameras, stop camera A (the SDK automatically deletes layer A), start camera B, and set the position and size of layer B.

  1. Stop camera A:

    // Note: Pass the streamId, not the deviceId. The streamId is the return value of the previous startCamera() call for camera A.
    pushClient.stopCamera(streamIdA);
  2. Start camera B:

    const streamIdB = await pushClient.startCamera(deviceId); // Pass the deviceId of camera B
  3. Set the position and size of layer B:

    videoEffectManager.setLayout([
      { streamId: streamIdB, x: 1280/2, y: 720/2, width: 1280, height: 720, zOrder: 1 }, // Set the size of camera B as needed
      ... // Other layer settings
    ]);

Note

The same principle applies when you switch between different screen sharing feeds. The steps are the same as for switching cameras.

Use in Vue3

The reactive state ref() in Vue3 deeply unwraps objects and nests each child object in a ref. This can corrupt the internal structure of the stream ingest instance object. Do not use ref() to store the Push SDK instance object. Instead, use a normal variable or shallowRef(). The following examples show how:

Use a variable

<script setup lang="ts">
  import { onMounted } from 'vue';
  import { AliRTSPusher } from 'aliyun-rts-pusher';
  import type { RtsClient } from 'aliyun-rts-pusher';

  let pushClient: RtsClient;
  onMounted(() => {
    pushClient = AliRTSPusher.createClient();
  })
</script>

Use shallowRef

<script setup lang="ts">
  import { onMounted, shallowRef } from 'vue';
  import { AliRTSPusher } from 'aliyun-rts-pusher';
  import type { RtsClient } from 'aliyun-rts-pusher';

  const pushClient = shallowRef<RtsClient>();
  onMounted(() => {
    pushClient.value = AliRTSPusher.createClient();
  })
</script>

Share a screen in Electron

Download the sample code.

After you decompress the package, the sample code folder is structured as follows:

+---demo-rts-pusher-electron
|       index.html ## HTML page
|       main.js ## Main process initialization JS. This file includes code to get the screen sharing sources.
|       package-lock.json
|       package.json
|       preload.js
|       README.md
|       renderer.js ## Rendering process JS. This file includes code that shows how to accept the sources passed by the main process, create a screen share, and start stream ingest.

Get screen sharing sources

To share a screen in Electron, you must first retrieve the available screen sharing sources. The following code in main.js provides an example. For more information about retrieving screen sharing sources, see Electron desktopCapturer.

  desktopCapturer.getSources({ types: ['screen', 'window'] })
    .then(async (sources) => {
      win.webContents.send('SET_SOURCE', sources);
    })
    .catch(e => {
      console.log(e);
    })
Note
  • After you retrieve the sources, you can specify chromeMediaSourceId in navigator.mediaDevices.getUserMedia. If your service does not require a specific sharing source, you do not need to retrieve the screen sharing sources. The system shares the current window by default.

  • Retrieve the list of sharing sources to allow users to select their desired source.

Capture

The renderer.js file contains the capture code.

// Start Capture button
$startBtn.addEventListener('click', async () => {
 
  // The passed sources
  console.log('ELECTRON API', window.electronAPI.sources);
  const sources = window.electronAPI.sources;

  const cameraStreamId = await pushClient.startCamera();
  const micStreamId = await pushClient.startMicrophone();

  // Screen sharing solution: Use native getUserMedia to get the stream, then use the addCustomStream method to add it to the SDK.
  const stream = await navigator.mediaDevices.getUserMedia({
      video: {
        mandatory: {
          chromeMediaSource: 'desktop',
          // chromeMediaSourceId: sources[0].id,
          minWidth: 1280,
          maxWidth: 1280,
          minHeight: 720,
          maxHeight: 720
        }
      },
      // Note: If you capture screen audio, do not enable the audio for the local preview <video> tag. This causes an echo due to loop capture. Keep the <video> tag muted, ingest the stream normally, and then use the stream pulling URL for preview.
      // audio: {
      //   mandatory: {
      //     chromeMediaSource: 'desktop',
      //   }
      // }
  });
  const screenStreamId = await pushClient.addCustomStream(stream);

  // Camera in the upper-left corner, screen share centered
  videoEffectManager.setLayout([
    { streamId: screenStreamId, x: 1280/2, y: 720/2, width: 1280, height: 720, zOrder: 1 },
    { streamId: cameraStreamId, x: 320/2, y: 180/2, width: 320, height: 180, zOrder: 2 },
  ]);
})
Note
  • pushClient.startCamera() captures the camera feed.

  • pushClient.startMicrophone() captures the microphone audio.

  • For more information, see API reference.

Stream ingest

The renderer.js file contains the stream ingest code. You may also need the Live streaming URL generator.

// Start Ingest button
$publishBtn.addEventListener('click', () => {
  pushClient.startPush('artc://xxxx');
})