Stream

Stream

Stream 音视频流,一个 Stream 中最多只能同时包含一个音频 track 和一个视频 track。
Stream 类是本地流 LocalStream 和远端流 RemoteStream 的基类,它包含本地流和远端流通用的方法。

Methods

(async) play(elementId, optionsopt) → {Promise}

Play the audio/video stream
This API creates an

  • Due to browsers’ autoplay policy, a PLAY_NOT_ALLOWED error may be returned when you call this API. In that case, display a window on the UI and, in the callback for the window’s clicking event, call resume() to resume audio/video playback.
Example
// For versions earlier than v4.8.4, capture and handle the 0x4043 error as follows.
stream.play('remote').then(() => {
  // autoplay success
}).catch((error) => {
  const errorCode = error.getCode();
  if (errorCode === 0x4043) {
    // If the `PLAY_NOT_ALLOWED` error occurs, display a window on the UI and, in the callback for the window’s clicking event, call `stream.resume` to resume audio/video playback.
    // stream.resume()
  }
});
// For v4.8.4 and later versions, we strongly recommend that you use the error callback of `Stream` to capture and handle the 0x4043 error.
stream.play('remote').catch(error => {});
stream.on('error', error => {
  const errorCode = error.getCode();
  if (errorCode === 0x4043) {
    // If the `PLAY_NOT_ALLOWED` error occurs, display a window on the UI and, in the callback for the window’s clicking event, call `stream.resume` to resume audio/video playback.
    // stream.resume()
  }
})
Parameters:
Name Type Attributes Description
elementId string | HTMLDivElement

HTML <div> stag ID or HTMLDivElement object in DOM. This method will create video/audio tag in elementId to play stream.

options object <optional>

Playback options

Properties
Name Type Description
objectFit string

Video fill mode. For details, see the CSS object-fit property.

  • 'contain': The video image is scaled as large as its long side can go. The blank area is filled with black bars. This mode ensures that the image is displayed in whole.
  • 'cover': The video image is scaled as large as the short side can go. The image fills the entire screen, but may be cropped.
  • 'fill': Ensures that the viewport is filled and the video content is displayed in its entirety, but does not guarantee that the video size remains proportional. The width and height of the video will be stretched to match the size of the viewport. (This option value is supported since v4.12.1)

The cover mode is used by default to play the video stream and the contain mode is used by default to the screen sharing stream.

muted boolean

Whether muting is required.

  • For local streams, muted defaults to true, preventing playback of sounds captured from the microphone.
mirror boolean

Whether to enable video mirroring preview. (This option is supported since v4.12.1)Note

  • For local video stream, mirror preview is enabled by default. It is recommended to enable mirroring when using the front camera and disable mirroring when using the rear camera.
  • For remote video stream, mirror preview is disabled by default.
  • For screen sharing streams, enabling mirror preview is not supported.
  • This Property is only valid for local preview, pushing the stream is no mirroring effect.
Throws:
Returns:
Type
Promise

stop()

Stop playing an audio/video stream

This API will also delete the audio and video tags created via play() from the HTML page.

(async) resume() → {Promise}

Resume playing an audio/video stream
NOTE

  • On some browsers, moving the div container passed in by play() may cause the audio and video players to pause. In that case, you need to call this API to resume playback.
  • If play() returns the PLAY_NOT_ALLOWED error due to the browser’s autoplay policy, display a window on the UI and, in the callback for the window’s clicking event, call this API to resume playback.
Example
stream.on('player-state-changed', event => {
  if (event.state === 'PAUSED') {
    // resume audio/video playback
    stream.resume();
  }
});
Throws:
Returns:
Type
Promise

close()

Close an audio/video stream

For local streams, this API will turn the camera off and release the camera and mic.

muteAudio() → {boolean}

Disable the audio track of a stream and keep the audio track, usually for temporary muting of local streams.

  • For local streams, this API will stop audio sending, and remote users will receive the Client.on('mute-audio') callback.
  • For remote streams, after this API is called, the local user will stop playing the remote user’s audio but will continue to receive audio data from the user.
Returns:
  • true: The audio track is disabled successfully.
  • false: Failed to disable the audio track as it does not exist
Type
boolean

muteVideo() → {boolean}

Disable the video track of a stream

  • For local streams, this API will stop video sending, and remote users will receive the Client.on('mute-video') callback. If video is captured from the camera, the camera will not be turned off by this API. To turn the camera off, call removeTrack() to remove the video track and then. MediaStreamTrack.stop() to disable video (turn the camera off).
  • For remote streams, after this API is called, the local user will stop playing the remote user’s video but will continue to receive video data from the user. If you do not want to receive video data, use Client.unsubscribe to unsubscribe, or Client.subscribe to subscribe to video only.
Returns:
  • true: The video track is disabled successfully.
  • false: Failed to disable the video track as it does not exist.
Type
boolean

unmuteAudio() → {boolean}

Enable the audio track of a stream

For local streams, this API will trigger the Client.on('unmute-audio') callback for remote users.

The audio track is enabled by default. If it is disabled via muteAudio(), you can call this API to enable the audio track again.

Returns:
  • true: The audio track is enabled successfully.
  • false: Failed to enable the audio track as it does not exist.
Type
boolean

unmuteVideo() → {boolean}

Enable the video track of a stream

For local streams, this API will trigger the Client.on('unmute-video') callback for remote users.

The video track is enabled by default. If it is disabled via muteVideo(), you can call this API to enable the video track again.

Returns:
  • true: The video track is enabled successfully.
  • false: Failed to enable the video track as it does not exist.
Type
boolean

getId() → {string}

Get the unique ID of a stream

Returns:

Id: unique ID of the stream

Type
string

getUserId() → {string}

Get the ID of the user to whom a stream belongs

Returns:

userId: user ID

Type
string

(async) setAudioOutput(deviceId)

Set the audio output device

  • No support for mobile devices.
Parameters:
Name Type Description
deviceId string

Device ID, which can be obtained via getSpeakers()

setAudioVolume(volume)

Set the playback volume

Parameters:
Name Type Description
volume double

Volume. Value range: 0.0-1.0. 0.0 means to mute playback, and 1.0 means to use the highest volume.

getAudioLevel() → {number}

Get the current volume
This API works only if there is audio data in the local stream or a remote stream. Before calling this API, you need to play the stream first.

Example
setInterval(() => {
  const level = stream.getAudioLevel();
  if (level >= 0.1) {
    console.log(`user ${stream.getUserId()} is speaking`);
  }
}, 200);
Returns:

audioLevel: volume

  • Value range: 0.0-1.0. Generally, a user is considered to be speaking if the value is greater than 0.
Type
number

hasAudio() → {boolean}

Get whether a stream has an audio track

  • If you need to get the Stream mute state, you need to listen to the Client.on('mute-audio') event for further processing.
Returns:
Type
boolean

hasVideo() → {boolean}

Get whether a stream has a video track

  • If you need to get the Stream mute state, you need to listen to the Client.on('mute-video') event for further processing.
Returns:
Type
boolean

getAudioTrack() → {MediaStreamTrack}

Get the audio track of a stream

Returns:

Audio tra

Type
MediaStreamTrack

getVideoTrack() → {MediaStreamTrack}

Get the video track of a stream

Returns:

Video tra

Type
MediaStreamTrack

getVideoFrame() → {String}

Get the current video frame
NOTE

  • This API works only if it is called after play() and the stream contains video.
Example
// Get the current video frame
const frame = stream.getVideoFrame();
if (frame) {
  const img = document.createElement('img');
  img.src = frame;
}
Returns:

dataURL of 'image/png' type

Type
String

on(eventName, handler, context)

Listen for Stream events
For the detailed event list, please see StreamEvent.

Example
function onPlayerStateChange(event) {
   console.log(`${event.type} player is ${event.state}`);
}
stream.on('player-state-changed', onPlayerStateChange);
Parameters:
Name Type Description
eventName string

Event name

handler function

Event handling method

context object

Context object

off(eventName, handler, context)

Stop listening for Stream events

Example
function onPlayerStateChange(event) {
   console.log(`${event.type} player is ${event.state}`);
}
stream.on('player-state-changed', onPlayerStateChange);
stream.off('player-state-changed', onPlayerStateChange);
Parameters:
Name Type Description
eventName string

Event name. If the wildcard '*' is passed in, all bound events will be unbound.

handler function

Event handling method

context object

Context object