The Stream object created by the createStream method.

A stream represents a published local or remote media stream object in a call session.

All Stream methods can be called for both local and remote streams if not specified.

Hierarchy

  • Stream

Index

Methods

addTrack

  • Adds the Audio or Video Track

    This method adds the audio or video tracks into the stream.

    When the track is added, the Client.on("stream-updated") is triggered on the remote client.

    example

    Sample Code

    var localStream = AgoraRTC.createStream({audio: true, video: false});
    localStream.addTrack(anotherStream.getVideoTrack());

    Note:

    • This method does not support Firefox and Safari.
    • A Stream object can have only one audio track and one video track at most.

    Parameters

    • track: MediaStreamTrack

      The track can be retrieved from the mediaStream method.

    Returns void

adjustAudioMixingVolume

  • adjustAudioMixingVolume(level: number): void
  • Adjusts Audio Mixing Volume

    Parameters

    • level: number

      The volume of the mixing audio. The value ranges between 0 and 100 (default).

    Returns void

close

  • close(): void
  • Closes the Audio/Video Stream

    This method closes the video/audio stream.

    After calling this method, the camera and microphone authorizations are reset.

    Returns void

disableAudio

  • disableAudio(): void
  • Disables the Audio

    DEPRECATED from v 2.5.1, use muteAudio instead.

    This method disables the audio track in the stream.

    It works only when the audio flag is true in the stream.

    Returns void

disableVideo

  • disableVideo(): void
  • Disables the Video

    DEPRECATED from v 2.5.1, use muteVideo instead.

    This method disables the video track in the stream.

    It works only when the video flag is true in the stream.

    Returns void

enableAudio

  • enableAudio(): void
  • Enables the Audio

    DEPRECATED from v 2.5.1, use unmuteAudio instead.

    This method enables the audio track in the stream.

    It works only when the audio flag is true in the stream.

    By default the audio track is enabled. If you call disableAudio, call this method to enable audio.

    Returns void

enableVideo

  • enableVideo(): void
  • Enables the Video

    DEPRECATED from v 2.5.1, use unmuteVideo instead.

    This method enables the video track in the stream.

    It works only when the video flag is true in the stream.

    By default the video track is enabled. If you call disableVideo, call this method to enable video.

    Returns void

getAudioLevel

  • getAudioLevel(): number | void
  • Retrieves the Current Audio Level

    This method retrieves the current audio level.

    Call setTimeout or setInterval to retrieve the local or remote audio change.

    example

    Sample Code

    setInterval(function() {
      var audioLevel = stream.getAudioLevel();
      // Use audioLevel to render the UI
    }, 100)

    This method does not apply to streams that contain no audio data and may result in warnings.

    Note:

    Due to browser policy changes, this method must be triggered by the user's gesture on the Chrome 70+ and Safari browser. See Autoplay Policy Changes for details.

    Returns number | void

    The audio level. The value range is [0,1].

getAudioMixingCurrentPosition

  • getAudioMixingCurrentPosition(): number | void
  • Retrieves the Current Position of the Audio Mixing

    Retrieves the playback position (ms) of the audio.

    Returns number | void

    Returns the current position of the audio mixing if successful.

getAudioMixingDuration

  • getAudioMixingDuration(): number | void
  • Retrieves Audio Mixing Duration

    Returns number | void

    Returns the audio mixing duration (ms) if successful.

getAudioTrack

  • Retrieves the Audio Track

    This method retrieves the audio track in the stream and can be used together with replaceTrack.

    Returns MediaStreamTrack | void

    If the stream contains an audio track, it will be returned in a MediaStreamTrack object.

getEffectsVolume

  • getEffectsVolume(): Array<object>
  • Gets the volume of the audio effects.

    example

    Sample code

    var volumes = stream.getEffectsVolume();
    volumes.forEach(function({soundId, volume}){
        console.log("SoundId", soundId, "Volume", volume);
    });

    Returns Array<object>

    Returns an array that contains soundId and volume. Each soundId has a correspondingvolume.

    • soundId: The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].
    • volume: Volume of the audio effect. The value range is [0,100].

getId

  • getId(): number
  • Retrieves the Stream ID

    This method retrieves the stream ID.

    example

    stream.getId()

    Returns number

getStats

  • getStats(callback: function): void
  • Gets Connection Statistics

    This method gets the connection statistics of the stream.

    Note:

    It may take some time to get some of the statistics.

    example

    Sample Code

    localStream.getStats((stats) => {
        console.log(`Local Stream accessDelay: ${stats.accessDelay}`);
        console.log(`Local Stream audioSendBytes: ${stats.audioSendBytes}`);
        console.log(`Local Stream audioSendPackets: ${stats.audioSendPackets}`);
        console.log(`Local Stream audioSendPacketsLost: ${stats.audioSendPacketsLost}`);
        console.log(`Local Stream videoSendBytes: ${stats.videoSendBytes}`);
        console.log(`Local Stream videoSendFrameRate: ${stats.videoSendFrameRate}`);
        console.log(`Local Stream videoSendPackets: ${stats.videoSendPackets}`);
        console.log(`Local Stream videoSendPacketsLost: ${stats.videoSendPacketsLost}`);
        console.log(`Local Stream videoSendResolutionHeight: ${stats.videoSendResolutionHeight}`);
        console.log(`Local Stream videoSendResolutionWidth: ${stats.videoSendResolutionWidth}`);
    });
    
    
    remoteStream.getStats((stats) => {
        console.log(`Remote Stream accessDelay: ${stats.accessDelay}`);
        console.log(`Remote Stream audioReceiveBytes: ${stats.audioReceiveBytes}`);
        console.log(`Remote Stream audioReceiveDelay: ${stats.audioReceiveDelay}`);
        console.log(`Remote Stream audioReceivePackets: ${stats.audioReceivePackets}`);
        console.log(`Remote Stream audioReceivePacketsLost: ${stats.audioReceivePacketsLost}`);
        console.log(`Remote Stream endToEndDelay: ${stats.endToEndDelay}`);
        console.log(`Remote Stream videoReceiveBytes: ${stats.videoReceiveBytes}`);
        console.log(`Remote Stream videoReceiveDecodeFrameRate: ${stats.videoReceiveDecodeFrameRate}`);
        console.log(`Remote Stream videoReceiveDelay: ${stats.videoReceiveDelay}`);
        console.log(`Remote Stream videoReceiveFrameRate: ${stats.videoReceiveFrameRate}`);
        console.log(`Remote Stream videoReceivePackets: ${stats.videoReceivePackets}`);
        console.log(`Remote Stream videoReceivePacketsLost: ${stats.videoReceivePacketsLost}`);
        console.log(`Remote Stream videoReceiveResolutionHeight: ${stats.videoReceiveResolutionHeight}`);
        console.log(`Remote Stream videoReceiveResolutionWidth: ${stats.videoReceiveResolutionWidth}`);
    });
    

    Parameters

    Returns void

getVideoTrack

  • Retrieves the Video Track

    This method retrieves the video track in the stream and can be used together with replaceTrack.

    Returns MediaStreamTrack | void

    If the stream contains a video track, it will be returned in a MediaStreamTrack object.

hasAudio

  • hasAudio(): boolean
  • Retrieves the Audio Flag

    This method retrieves the audio flag and only works for local streams.

    Returns boolean

    • true: The stream contains audio data.
    • false: The stream does not contain audio data.

hasVideo

  • hasVideo(): boolean
  • Retrieves the Video Flag

    This method retrieves the video flag and only works for local streams.

    Returns boolean

    • true: The stream contains video data.
    • false: The stream does not contain video data.

init

  • init(onSuccess?: function, onFailure?: function): void
  • Initializes the Stream Object

    This method initializes the local stream object.

    If this method fails, see getUserMedia Exceptions for error information.

    Some errors might be returned in the callback, for example: {type: "error", msg: "NotAllowedError", info: "Permission denied"}.

    The possible error information in the msg field includes:

    • NotAllowedError: User refuses to grant access to camera or audio resource.
    • MEDIA_OPTION_INVALID: The camera is occupied or the resolution is not supported (on browsers in early versions).
    • DEVICES_NOT_FOUND: No device is found.
    • NOT_SUPPORTED: The browser does not support using camera and microphone.
    • PERMISSION_DENIED: The device is disabled by the browser or the user has denied permission of using the device.
    • CONSTRAINT_NOT_SATISFIED: The settings are illegal (on browsers in early versions).
    • PluginNotInstalledProperly: A screen-sharing request is made with no plugin installed or with a wrong extensionId on the Chrome browser.
    • UNDEFINED: Undefined error.

    The info field shows the extra information for the error. If no more extra information, its value will be null.

    example

    Sample Code

    init(function() {
        console.log("local stream initialized");
        // publish the stream
        //……
    }, function(err) {
        console.error("local stream init failed ", err);
        //error handling
    });
    

    Parameters

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: object): void
        • Parameters

          • err: object
            • Optional info?: string
            • msg: string
            • type: "warning" | "error"

          Returns void

    Returns void

isPlaying

  • isPlaying(): boolean
  • Returns Whether the Stream is Playing

    Returns boolean

    • true: The stream is being rendered or playing on the page.
    • false: The stream is neither being rendered nor playing on the page.

muteAudio

  • muteAudio(): void
  • Disables the Audio

    This method disables the audio track in the stream.

    • For local streams, this method call stops sending audio and triggers the Client.on("mute-audio") callback on the remote client.
    • For remote streams, the SDK still receives audio but stops playing it after you call this method.

    Note: For local streams, it works only when the audio flag is true in the stream.

    Returns void

    • true: Success.
    • false: Failure. Possible reasons include no audio, stream not initialized, and audio track already disabled.

muteVideo

  • muteVideo(): void
  • Disables the Video

    This method disables the video track in the stream.

    • For local streams, this method call stops sending video and triggers the Client.on("mute-video") callback on the remote client.
    • For remote streams, the SDK still receives video but stops playing it after you call this method.

    Note: For local streams, it works only when the video flag is true in the stream.

    Returns void

    • true: Success.
    • false: Failure. Possible reasons include no video, stream not initialized, and video track already disabled.

on

  • on(event: "accessAllowed", callback: function): void
  • on(event: "accessDenied", callback: function): void
  • on(event: "stopScreenSharing", callback: function): void
  • on(event: "videoTrackEnded", callback: function): void
  • on(event: "audioTrackEnded", callback: function): void
  • on(event: "audioMixingPlayed", callback: function): void
  • on(event: "audioMixingFinished", callback: function): void
  • on(event: "player-status-change", callback: function): void
  • Occurs when the user gives access to the camera and microphone.

    Parameters

    • event: "accessAllowed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the user denies access to the camera and microphone.

    Parameters

    • event: "accessDenied"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when screen-sharing stops.

    Parameters

    • event: "stopScreenSharing"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the video track no longer provides data to the stream.

    Possible reasons include device removal and deauthorization. See Media​Stream​Track​.onended.

    Parameters

    • event: "videoTrackEnded"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the audio track no longer provides data to the stream.

    Possible reasons include device removal and deauthorization. See Media​Stream​Track​.onended.

    Parameters

    • event: "audioTrackEnded"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the audio mixing stream playback starts/resumes.

    Note: This callback is triggered when the audio mixing stream is loaded and starts playing, or when the paused audio mixing stream resumes playing.

    Parameters

    • event: "audioMixingPlayed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the last audio mixing stream playback finishes.

    Parameters

    • event: "audioMixingFinished"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the stream playback status changes.

    On Windows, frequent DOM manipulations might cause the browser to pause the Chrome player. To avoid this, you can listen for this event and call the Stream.resume method to resume the playback.

    This callback has the following properties.

    • isErrorState: Whether or not the playback fails.
      • true: The playback fails.
      • false: The playback is normal.
    • mediaType: The player type.
      • "audio": Audio player.
      • "video": Video player.
    • status: The playback status.
      • "play": Playing.
      • "aborted": The player is removed before the stream is played successfully.
      • "paused": The player is stopped.
    • reason: The reason why the playback status changes. Usually, this value is the event that triggers the status change. Possible values include the following:
      • "playing": The playback starts. See HTMLMedia​Element: playing event.
      • "stalled": The failure might be caused by the browser policy. See stalled event.
      • "pause": The stream playback might be paused by the user. See pause event.
      • "suspend": The failure might be caused by the browser policy. See suspend event.
      • "canplay": Some browsers automatically stop the playback when the playback window is not displayed on the screen. See canplay event.
      • "timer": The playback failure is caused by an unknown reason and captured by the internal timer.
    example

    Sample Code

     stream.on("player-status-change", function(evt){
         if (evt.isErrorState && evt.status === "paused"){
             console.error(`Stream is paused unexpectedly. Trying to resume...`);
             stream.resume().then(function(){
                 console.log(`Stream is resumed successfully`);
             }).catch(function(e){
                 console.error(`Failed to resume stream. Error ${e.name} Reason ${e.message}`);
             });
         }
     });
    

    Parameters

    • event: "player-status-change"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

pauseAllEffects

  • pauseAllEffects(callback?: function): void
  • Pauses all audio effects.

    example

    Sample code

    stream.pauseAllEffects(function(err){
        if (err){
            console.error("Failed to pause effects, reason: ", err);
        }else{
            console.log("Effects are paused successfully");
        }
    });

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

pauseAudioMixing

  • pauseAudioMixing(callback?: function): void
  • Pauses Audio Mixing

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

pauseEffect

  • pauseEffect(soundId: number, callback?: function): void
  • Pauses a specified audio effect.

    example

    Sample code

    // When the audio effect 1 is playing
    stream.pauseEffect(1, function(err){
        if (err){
            console.error("Failed to pause Effect, reason: ", err);
        }else{
            console.log("Effect is paused successfully");
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

play

  • play(HTMLElementID: string, option?: object, callback?: function): void
  • Plays the Audio/Video Stream

    This method plays the video or audio stream.

    Note:

    Due to browser policy changes, this method must be triggered by the user's gesture on the Chrome 70+ and Safari browsers. See Autoplay Policy Changes for details.

    example

    Sample Code

    stream.play("agora_remote", {fit: "contain"}, function(errState){
        if (errState && errState.status !== "aborted"){
            // The playback fails, probably due to browser policy. You can resume the playback by user gesture.
        }
    }); // stream will be played in the element with the ID agora_remote

    Parameters

    • HTMLElementID: string

      Represents the HTML element ID. Digits and letters in the ASCII character set, “_”, “-", and ".". The string length must be greater than 0 and less than 256 bytes.

    • Optional option: object

      Options for playing the stream.

      • Optional fit?: "cover" | "contain"

        Video display mode:

        • "cover": Uniformly scale the video until it fills the visible boundaries (cropped). One dimension of the video may have clipped contents. Refer to the cover option of object-fit in CSS.

        • "contain": Uniformly scale the video until one of its dimension fits the boundary (zoomed to fit). Areas that are not filled due to the disparity in the aspect ratio will be filled with black. Refer to the contain option of object-fit in CSS.

        For local streams, by default the cover mode is used for video playing and the contain mode is used for screen sharing; for remote streams, by default the cover mode is used.

      • Optional muted?: boolean

        Sets whether to mute the playing stream.

        The muted flag can be used as a workaround for the browser's autoplay policy.

        On Chrome 70+ and Safari, a video stream with sound does not play until triggered by a user gesture. If you want to play the video anyway without a user gesture, you can set the muted flag to true, so that the video is automatically played without sound.

        For more information, see Autoplay Policy Changes.

    • Optional callback: function

      Whether or not the playback succeeds.

      • err

    Returns void

playEffect

  • playEffect(options: object, callback?: function): void
  • Plays a specified audio effect.

    This method supports playing multiple audio effect files at the same time, and is different from startAudioMixing.

    You can use this method to add specific audio effects for specific scenarios. For example, gaming.

    Note:

    • Due to web browser autoplay policy changes, this method must be triggered by a user gesture on Chrome 70+ and Safari web browsers. See Autoplay Policy Changes for details.
    • This method supports the following web browsers:
      • Safari 12 and later
      • Chrome 65 and later
      • Firefox 66 and later
    • Call this method when you are in a channel. Otherwise, it may cause issues.
    example

    Sample code

    stream.playEffect({
         soundId: 1,
        filePath: "biu.mp3"
    }, function(error) {
        if (error) {
            // Error handling
            return;
        }
        // Process after the method call succeeds
    });
    

    Parameters

    • options: object

      Audio effect options.

      • Optional cycle?: number

        The number of playback loops (only supported on Chrome 65 and later).

        A positive integer. The value range is [1,10000]. The default value is 1.

      • filePath: string

        The URL of the online audio effect file.

        The URL must contain ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

        Supported audio formats: MP3, AAC, and other audio formats depending on the browser.

      • soundId: number

        The ID of the specified audio effect.

        A positive integer. The value range is [1,10000]. Each audio effect has a unique ID.

        If the audio effect is preloaded into the memory through the preloadEffect method, ensure that the soundId value is set to the same value as in preloadEffect.

    • Optional callback: function

      The callback of this method:

      • null: the method call succeeds.
      • err: the method call fails.

      Note:

      The callbacks of the audio effect methods all use the Node.js callback pattern.

        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

preloadEffect

  • preloadEffect(soundId: number, filePath: string, callback?: function): void
  • Preloads a specified audio effect file into the memory.

    To ensure smooth communication, limit the size of the audio effect file.

    example

    Sample code

    stream.preloadEffect(1, "https://web-demos-static.agora.io/agora/smlt.flac", function(err){
        if (err){
            console.error("Failed to preload effect, reason: ", err);
        }else{
            console.log("Effect is preloaded successfully");
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • filePath: string

      The URL of the online audio effect file. Supports MP3, AAC, and other audio formats depending on the browser.

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

removeTrack

  • Removes the Audio or Video Track

    This method removes the audio or video tracks from the stream.

    When the track is removed, the Client.on("stream-updated") callback is triggered on the remote client.

    Note:

    • If you need to change both the audio and video tracks, we recommend using the replaceTrack method instead.
    • This method does not support Firefox and Safari.
    example

    Sample Code

    var localStream = AgoraRTC.createStream({audio: true, video: true});
    localStream.removeTrack(localStream.getAudioTrack());

    Parameters

    • track: MediaStreamTrack

      The track can be retrieved from the mediaStream method.

    Returns void

replaceTrack

  • replaceTrack(MediaStreamTrack: MediaStreamTrack, onSuccess?: function, onFailure?: function): void
  • Replaces the Audio/Video Track

    This method replaces the audio or video MediaStreamTrack in the local stream.

    After the local stream is published, you can use this method to switch the cameras, or switch between the microphone and the music player.

    The new track can be retrieved by getUserMedia, MediaElement.captureStream or other methods.

    The replaced track will be stopped.

    Note:

    • Supports Chrome 65+, Safari, and latest Firefox.
    • This method might not take effect on some mobile devices.
    • Firefox does not support switching audio tracks between different microphones. You can replace the audio track from the microphone with an audio file, or vice versa.
    • Replacing audio tracks from external audio devices may not be fully supported on Safari.
    • The subscriber will not be notified if the track gets replaced.
    • Agora recommends you use switchDevice to switch the media input devices.
    example

    Sample Code

    // Suppose we have a localStream1
    localStream2 = AgoraRTC.createStream({video: true, cameraId: "XXX"});
    localStream2.setVideoProfile('<same as localStream1>')
    localStream2.init(function(){
        var newVideoTrack = localStream2.getVideoTrack();
        localStream1.replaceTrack(newVideoTrack);
    });

    Parameters

    • MediaStreamTrack: MediaStreamTrack

      The new track.

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails. The following are common errors:

      • "INVALID_TRACK" and "INVALID_TRACK_TYPE": The MediaStreamTrack object cannot be recognized.
      • "MEDIASTREAM_TRACK_NOT_FOUND": The track to be replaced is not found, for example, replacing a video track in an audio-only stream.
      • "NO_STREAM_FOUND": The local stream object is not found.
        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

resume

  • resume(): Promise<any>
  • Resumes the Audio/Video Stream Playback

    This method can be used when the playback fails after calling the Stream.play method. In most cases, the playback is stopped due to the browser policy.

    This method needs to be triggered by a user gesture. See Autoplay Policy Changes for more information.

    Returns Promise<any>

resumeAllEffects

  • resumeAllEffects(callback?: function): void
  • Resumes playing all audio effects.

    example

    Sample code

    stream.resumeAllEffects(function(err){
        if (err){
            console.error("Failed to resume effects, reason: ", err);
        }else{
            console.log("Effects are resumed successfully");
        }
    });

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

resumeAudioMixing

  • resumeAudioMixing(callback?: function): void
  • Resumes Audio Mixing

    When the audio mixing file playback resumes, the SDK triggers the Stream.on("audioMixingPlayed") callback on the local client.

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

resumeEffect

  • resumeEffect(soundId: number, callback?: function): void
  • Resumes playing a specified audio effect.

    example

    Sample code

    // When the audio effect 1 is paused
    stream.resumeEffect(1, function(err){
        if (err){
            console.error("Failed to resume Effect, reason: ", err);
        }else{
            console.log("Effect is resumed successfully");
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

setAudioMixingPosition

  • setAudioMixingPosition(position: number, callback?: function): void
  • Sets the Audio Mixing Position

    Sets the playback position of the audio mixing file to a different start position (by default plays from the beginning).

    Parameters

    • position: number

      The time (ms) to start playing the audio mixing file, an integer. The value range is [0,100000000].

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

setAudioOutput

  • setAudioOutput(deviceId: string, onSuccess?: function, onFailure?: function): void
  • Sets the Audio Output

    This method sets the audio output device for the remote stream. You can use it to switch between the speakerphones. It can be called either before or after the remote stream is played.

    Note:

    Only Chrome 49 or later supports this function.

    Parameters

    • deviceId: string

      The device ID can be retrieved from getDevices, whose kind should be "audiooutput". The retrieved ID is ASCII characters, and the string length is greater than 0 and less than 256 bytes.

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

setAudioProfile

  • setAudioProfile(profile: "speech_low_quality" | "speech_standard" | "music_standard" | "standard_stereo" | "high_quality" | "high_quality_stereo"): void
  • Sets the Audio Profile

    This method sets the audio profile of the local stream.

    It is optional and works only when called before Stream.init. The default value is "music_standard".

    Note:

    Due to the limitations of browsers, some browsers may not be fully compatible with the audio profile you set.

    • Firefox does not support setting the audio encoding rate.
    • Safari does not support stereo audio.
    • Google Chrome does not support playing stereo audio, but supports sending a stereo audio stream. If the audio profile is set to stereo, the AEC, AGC, and ANS options in audioProcessing are automatically disabled.

    Parameters

    • profile: "speech_low_quality" | "speech_standard" | "music_standard" | "standard_stereo" | "high_quality" | "high_quality_stereo"

      The audio profile has the following options:

      • "speech_low_quality": Sample rate 16 kHz, mono, encoding rate 24 Kbps.
      • "speech_standard": Sample rate 32 kHz, mono, encoding rate 24 Kbps.
      • "music_standard": Sample rate 48 kHz, mono, encoding rate 40 Kbps.
      • "standard_stereo": Sample rate 48 kHz, stereo, encoding rate 64 Kbps.
      • "high_quality": Sample rate 48 kHz, mono, encoding rate 128 Kbps.
      • "high_quality_stereo": Sample rate 48 kHz, stereo, encoding rate 192 Kbps.

    Returns void

setAudioVolume

  • setAudioVolume(volume: number): void
  • Sets the Volume

    This method set the volume for the remote stream.

    It can be called either before or after the remote stream is played.

    Parameters

    • volume: number

      Ranges from 0 (muted) to 100 (loudest).

    Returns void

setEffectsVolume

  • setEffectsVolume(volume: number, callback?: function): void
  • Sets the volume of the audio effects.

    example

    Sample code

    stream.setEffectsVolume(0, function(err){
        if (err){
            console.error("Failed to set effects volume, reason: ", err);
        }else{
            console.log("Effects volume is set successfully");
        }
    });

    Parameters

    • volume: number

      Volume of the audio effect. The value range is [0,100].The default value is 100 (the original volume).

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

setScreenProfile

  • setScreenProfile(profile: string): void
  • Sets the Screen Profile

    This method sets the profile of the screen in screen-sharing.

    Parameters

    • profile: string

      The screen profile. See the following table for details.

      Screen Profile Definition

      Screen Profile Resolution Frame Rate
      480p_1 640 × 480 5
      480p_2 640 × 480 30
      720p_1 1280 × 720 5
      720p_2 1280 × 720 30
      1080p_1 1920 × 1080 5
      1080p_2 1920 × 1080 30

      Note:

      Due to limitations of some devices and browsers, the resolution you set may fail to take effect and get adjusted by the browser. In this case, billings will be calculated based on the actual resolution.

    Returns void

setVideoEncoderConfiguration

  • Customizes the Video Encoder Configuration

    You can use this method to customize the video resolution, frame rate, and bitrate of the local stream. This method can be called before or after Stream.init.

    Note:

    • Do not call this method when publishing streams.
    • On some iOS devices, when you update the video encoder configuration after Stream.init, black bars might appear around your video.
    • The actual resolution, frame rate, and bitrate depend on the device, see Media​Stream​Track​.apply​Constraints() for more information.
    • This method works on Chrome 63 or later and is not fully functional on other browsers with the following issues:
      • The frame rate setting does not take effect on Safari 12 or earlier.
      • Safari 11 or earlier only supports specific resolutions.
      • Safari on iOS does not support low resolutions in H.264 codec.
    example

    Sample Code

         stream.setVideoEncoderConfiguration({
             // Video resolution
             resolution: {
                 width: 640,
                 height: 480
             },
             // Video encoding frame rate. We recommend 15 fps. Do not set this to a value greater than 30.
             frameRate: {
                 min: 15,
                 max: 30
             },
             // Video encoding bitrate.
             bitrate: {
                 min: 1000,
                 max: 5000
             }
         });

    Parameters

    Returns void

setVideoProfile

  • setVideoProfile(profile: string): void
  • Sets the Video Profile

    This method sets the video encoding profile for the local stream. Each video encoding profile includes a set of parameters, such as the resolution, frame rate, and bitrate. The default value is "480p_1".

    This method is optional and is usually called before Stream.init. From v2.7, you can also call this method after Stream.init to change the video encoding profile.

    Note:

    • Do not call this method when publishing streams.
    • On some iOS devices, when you update the video profile after Stream.init, black bars might appear around your video.
    • Changing the video profile after Stream.init works only on Chrome 63 or later and Safari 11 or later.
    example

    setVideoProfile("480p");

    Parameters

    • profile: string

      The video profile. See the following table for its definition and supported profiles in different scenarios.

      Video Profile Definition

      Video profile Resolution Frame rate (fps) Bitrate (Kbps) Chrome Firefox Safari
      120p 160 × 120 15 65
      120p_1 160 × 120 15 65
      120p_3 120 × 120 15 50
      180p 320 × 180 15 140
      180p_1 320 × 180 15 140
      180p_3 180 × 180 15 100
      180p_4 240 × 180 15 120
      240p 320 × 240 15 200
      240p_1 320 × 240 15 200
      240p_3 240 × 240 15 140
      240p_4 424 × 240 15 220
      360p 640 × 360 15 400
      360p_1 640 × 360 15 400
      360p_3 360 × 360 15 260
      360p_4 640 × 360 30 600
      360p_6 360 × 360 30 400
      360p_7 480 × 360 15 320
      360p_8 480 × 360 30 490
      360p_9 640 × 360 15 800
      360p_10 640 × 360 24 800
      360p_11 640 × 360 24 1000
      480p 640 × 480 15 500
      480p_1 640 × 480 15 500
      480p_2 640 × 480 30 1000
      480p_3 480 × 480 15 400
      480p_4 640 × 480 30 750
      480p_6 480 × 480 30 600
      480p_8 848 × 480 15 610
      480p_9 848 × 480 30 930
      480p_10 640 × 480 10 400
      720p 1280 × 720 15 1130
      720p_1 1280 × 720 15 1130
      720p_2 1280 × 720 30 2000
      720p_3 1280 × 720 30 1710
      720p_5 960 × 720 15 910
      720p_6 960 × 720 30 1380
      1080p 1920 × 1080 15 2080
      1080p_1 1920 × 1080 15 2080
      1080p_2 1920 × 1080 30 3000
      1080p_3 1920 × 1080 30 3150
      1080p_5 1920 × 1080 60 4780
      1440p 2560 × 1440 30 4850
      1440p_1 2560 × 1440 30 4850
      1440p_2 2560 × 1440 60 7350
      4K 3840 × 2160 30 8910
      4K_1 3840 × 2160 30 8910
      4K_3 3840 × 2160 60 13500

      Note:

      • Whether 1080 resolution or above can be supported depends on the device. If the device cannot support 1080p, the actual frame rate is lower than the one listed in the table. Agora optimizes the video on low-end devices.

      • With the update of web browsers, this table might not reflect all the supported profiles for each browser. The actual support is subject to the device and web browser version.

      • Some versions of some web browsers might not support all the video profiles listed in the table. In this case, we recommend you use the mainstream video profiles (the ones with the _1 suffix in the above table).

      • The Safari browser does not support modifying the video frame rate (30 fps by default). If you set a frame rate other than 30 fps on Safari, the browser may change or reject your setting.

      • Due to limitations of some devices and browsers, the resolution you set may fail to take effect and get adjusted by the browser. In this case, billings are calculated based on the actual resolution.

    Returns void

setVolumeOfEffect

  • setVolumeOfEffect(soundId: number, volume: number, callback?: function): void
  • Sets the volume of a specified audio effect.

    example

    Sample code

    // When the audio effect 1 is loaded
    stream.setVolumeOfEffect(1, 50, function(err){
        if (err){
            console.error("Failed to set volume of Effect, reason: ", err);
        }else{
            console.log("Effect volume is set to", 50);
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • volume: number

      Volume of the audio effect. The value range is [0,100].The default value is 100 (the original volume).

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

startAudioMixing

  • startAudioMixing(options: object, callback?: function): void
  • Starts Audio Mixing

    This method mixes the specified online audio file with the audio stream from the microphone; or, it replaces the microphone’s audio stream with the specified online audio file.

    You can specify the number of playback loops and play time duration.

    When the audio mixing file playback starts, the SDK triggers the Stream.on("audioMixingPlayed") callback on the local client.

    When the audio mixing file playback finishes, the SDK triggers the Stream.on("audioMixingFinished") callback on the local client.

    Note:

    • This method supports the following browsers:
      • Safari 12 and later
      • Chrome 65 and later
      • Firefox 66 and later
    • Call this method when you are in a channel, otherwise, it may cause issues.
    • Due to browser policy changes, this method must be triggered by the user's gesture on the Chrome 70+ and Safari browser. See Autoplay Policy Changes for details.
    example

    Sample Code

    stream.startAudioMixing({
        filePath: 'example.mp3'
    }, function(error) {
        if (error) {
            // Error handling
            return;
        }
        // Processes after stream playing
    })
    

    Parameters

    • options: object

      Audio mixing settings.

      • Optional cacheResource?: boolean

        Whether or not to store the audio mixing file in the cache.

        • true: (default) store the audio mixing file in the cache to speed up mixing this file the next time.
        • false: do not store the audio mixing file in the cache to save RAM.
      • Optional cycle?: number

        Number of playback loops (only supports Chrome 65+)

        A positive integer. The value range is [1,10000]. The default value is 1.

      • filePath: string

        Path of the online audio file to mix. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

        Supported audio formats: mp3, aac, and other audio formats depending on the browser.

      • Optional loop?: boolean

        Whether the audio mixing file loops infinitely.

        • true: The audio mixing file loops infinitely. Do not use this option if cycle is specified.
        • false: (Default) Disables the infinite loops.
      • playTime: number

        Sets the playback position (ms) of the audio mixing file. An integer, and the value range is [0,100000000].

        If you need to play the file from the beginning, set this paramter to 0.

      • Optional replace?: boolean

        Whether the online audio file replaces the local audio stream.

        • true: The content of the online audio file replaces the audio stream from the microphone.
        • false: (Default) The online audio file is mixed with the audio stream from the microphone.

        Note:

        Safari does not support this parameter.

    • Optional callback: function

      The callback of this method:

      • null: The method succeeds.

      • err: The method fails. Possible errors:

        • "BROWSER_NOT_SUPPORT": Does not support the current browser.
        • "LOAD_AUDIO_FAILED": Fails to load the online audio file.
        • "CREATE_BUFFERSOURCE_FAILED": Fails to create buffer for audio mixing.

      Note: The callbacks of the other audio mixing methods are the same as this one, using the Node.js callback pattern.

        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

stop

  • stop(): void
  • Stops the Audio/Video Stream Playback

    Call this method to stop playing the stream set by Stream.play.

    Returns void

stopAllEffects

  • stopAllEffects(callback?: function): void
  • Stops playing all audio effects.

    example

    Sample code

    stream.stopAllEffects(function(err){
        if (err){
            console.error("Failed to stop effects, reason: ", err);
        }else{
            console.log("Effects are stopped successfully");
        }
    });

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

stopAudioMixing

  • stopAudioMixing(callback?: function): void
  • Stops Audio Mixing

    When the audio mixing file playback is stopped, the SDK triggers the Stream.on("audioMixingFinished") callback on the local client.

    Parameters

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

stopEffect

  • stopEffect(soundId: number, callback?: function): void
  • Stops playing a specified audio effect.

    example

    Sample code

    // When the audio effect 1 is playing
    stream.stopEffect(1, function(err){
        if (err){
            console.error("Failed to stop Effect, reason: ", err);
        }else{
            console.log("Effect is stopped successfully");
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

switchDevice

  • switchDevice(type: "audio" | "video", deviceId: string, onSuccess?: function, onFailure?: function): void
  • Switches the Media Input Device

    This method switches between the media input devices:

    • Audio input devices, such as microphones.
    • Video input devices, such as cameras.

    If you call this method after publish, there is no need to re-publish the stream after switching the device.

    This method does not support the following scenarios:

    Note:

    This method might not take effect on some mobile devices.

    Parameters

    • type: "audio" | "video"

      Type of the device: "audio" or "video".

    • deviceId: string

      Device ID, which can be retrieved from getDevices. The retrieved ID is ASCII characters, and the string length is greater than 0 and less than 256 bytes.

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

unloadEffect

  • unloadEffect(soundId: number, callback?: function): void
  • Releases a specified preloaded audio effect from the memory.

    example

    Sample code

    // When the audio effect 1 is loaded
    stream.unloadEffect(1, function(err){
        if (err){
            console.error("Failed to unload effect, reason: ", err);
        }else{
            console.log("Effect is unloaded successfully");
        }
    });

    Parameters

    • soundId: number

      The ID of the audio effect. Each audio effect has a unique ID. The value range is [1,10000].

    • Optional callback: function
        • (err: string | null): void
        • Parameters

          • err: string | null

          Returns void

    Returns void

unmuteAudio

  • unmuteAudio(): void
  • Enables the Audio

    This method enables the audio track in the stream.

    If you call this method to enable the audio track for local streams, the Client.on("unmute-audio") callback is triggered on the remote client.

    Note: For local streams, it works only when the audio flag is true in the stream.

    By default the audio track is enabled. If you call muteAudio, call this method to enable audio.

    Returns void

    • true: Success.
    • false: Failure. Possible reasons include no audio, stream not initialized, and audio track already enabled.

unmuteVideo

  • unmuteVideo(): void
  • Enables the Video

    This method enables the video track in the stream.

    If you call this method to enable the audio track for local streams, the Client.on("unmute-video") callback is triggered on the remote client.

    Note: For local streams, it works only when the video flag is true in the stream.

    By default the video track is enabled. If you call muteVideo, call this method to enable video.

    Returns void

    • true: Success.
    • false: Failure. Possible reasons include no video, stream not initialized, and video track already enabled.