Configure on-demand publishing and subscription
ApsaraVideo Real-time Communication (ARTC) SDK for Web allows you to control when to publish your audio and video streams and when to subscribe to streams from other users, rather than relying on the default automatic behavior.
By default, the SDK automatically publishes your stream after you join a channel and subscribes to streams from remote users. To publish and subscribe on demand, use the methods in the following sections.
Publish audio and video streams on demand
Call methods such as publishLocalVideoStream to disable automatic publishing before calling joinChannel.
// Make sure that an AliRtcEngine instance is created.
// Disable automatic publishing of video streams.
aliRtcEngine.publishLocalVideoStream(false);
// Disable automatic publishing of audio streams.
aliRtcEngine.publishLocalAudioStream(false);
// Disable automatic publishing of screen-sharing streams.
aliRtcEngine.publishLocalScreenShareStream(false);
After you disable automatic publishing, no stream is ingested even if the camera, microphone, or screen sharing is active. To publish a stream, call the corresponding method with the parameter set to true.
Subscribe to audio and video streams on demand
Call methods such as setDefaultSubscribeAllRemoteAudioStreams to disable automatic subscription before calling joinChannel.
// Make sure that an AliRtcEngine instance is created.
// Disable automatic subscription to audio streams.
aliRtcEngine.setDefaultSubscribeAllRemoteAudioStreams(false);
// Disable automatic subscription to video streams and screen-sharing streams.
aliRtcEngine.setDefaultSubscribeAllRemoteVideoStreams(false);
After you disable automatic subscription, call subscribeRemoteMediaStream to subscribe to a specific stream.
// Use npm to import the AliRtcVideoTrack object.
import { AliRtcVideoTrack } from 'aliyun-rtc-sdk';
// Alternatively, import the object from the window.
// const AliRtcVideoTrack = window.AliRtcEngine.AliRtcVideoTrack;
// In this example, you subscribe to the user after the remoteUserOnLineNotify event that you listen to is triggered.
// In actual scenarios, you can determine whether you want to subscribe to the user based on your requirements.
aliRtcEngine.on('remoteUserOnLineNotify', (userId) => {
// Subscribe to all streams of the user, including video streams, audio streams, and screen-sharing streams. This way, no error occurs if specific types of streams are not ingested.
// When the user ingests a stream, you are subscribed to the stream.
aliRtcEngine.subscribeRemoteMediaStream(
userId,
AliRtcVideoTrack.AliRtcVideoTrackBoth,
true,
true
);
});
aliRtcEngine.on('remoteUserOffLineNotify', (userId) => {
// When the user leaves the channel, you can cancel the subscription.
});