The Client object returned by the createClient method provides access to much of the core AgoraRTC functionality.

Hierarchy

  • Client

Index

Methods

addInjectStreamUrl

  • Injects an Online Media Stream to a Live Broadcast

    The streamInjectedStatus callback returns the inject status.If this method is called successfully, the server pulls the voice or video stream and injects it into a live channel. This is applicable to scenarios where all of the audience members in the channel can watch a live show and interact with each other.

    Parameters

    • url: string

      URL address of the live streaming. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes. Valid protocols are RTMP, HLS, and FLV.

      • Supported FLV audio codec type: AAC.
      • Supported FLV video codec type: H.264 (AVC).
    • config: InjectStreamConfig

      Configuration of the inject stream, see InjectStreamConfig for details.

    Returns void

configPublisher

  • configPublisher(width: number, height: number, framerate: number, bitrate: number, publisherUrl: string): void
  • Configures the CDN Live Streaming

    DEPRECATED

    Agora recommends using the following methods instead:

    This method configures the CDN live streaming before joining a channel.

    Note:

    Call configPublisher before Client.join.

    example

    Sample Code

    client.configPublisher({
      width: 360,
      height: 640,
      framerate: 30,
      bitrate: 500,
      publishUrl: "rtmp://xxx/xxx/"
    });

    Parameters

    • width: number

      Width of the output data stream set for CDN Live, 360 is the default value. A positive integer, and the value range is [1,10000].

    • height: number

      Height of the output data stream set for CDN Live, 640 is the default value. A positive integer, and the value range is [1,10000].

    • framerate: number

      Frame rate of the output data stream set for CDN Live, 15 fps is the default value. A positive integer, and the value range is [1,10000].

    • bitrate: number

      Bitrate of the output data stream set for CDN Live, 500 kbps is the default value. A positive integer, and the value range is [1,10000000].

    • publisherUrl: string

      The push-stream address for the picture-in-picture layouts, null is the default value. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

    Returns void

disableDualStream

  • disableDualStream(onSuccess?: function, onFailure?: function): void
  • Disables Dual Streams

    This method disables dual streams.

    example

    Sample Code

    client.disableDualStream(function() {
      console.log("Disable dual stream success!")
    }, function(err) {
      console.log(err)
    })

    Parameters

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

enableAudioVolumeIndicator

  • enableAudioVolumeIndicator(): void
  • Enables Volume Indicator

    This method enables the SDK to report the active remote users who are speaking and their volume regularly.

    If this method is enabled, the SDK will return the volumes every two seconds, regardless of whether there are active speakers.

    Note:

    • If you have multiple web pages running the Web SDK, this function might not work.
    example

    Sample Code

    client.enableAudioVolumeIndicator(); // Triggers the "volume-indicator" callback event every two seconds.
    client.on("volume-indicator", function(evt){
        evt.attr.forEach(function(volume, index){
                console.log(#{index} UID ${volume.uid} Level ${volume.level});
        });
    });

    Returns void

enableDualStream

  • enableDualStream(onSuccess?: function, onFailure?: function): void
  • Enables Dual Stream

    This method enables the dual-stream mode on the publisher side.

    Dual streams are a hybrid of a high-video stream and a low-video stream:

    • High-video stream: high bitrate, high resolution
    • Low-video stream: low bitrate, low resolution
    example

    Sample Code

    client.enableDualStream(function() {
      console.log("Enable dual stream success!")
    }, function(err) {
      console,log(err)
    })

    Note:

    This method does not apply to the following scenarios:

    • The stream is created by defining the audioSource and videoSource properties.
    • Audio-only mode (audio: true, video: false)
    • Safari browser on iOS
    • Screen-sharing scenario

    Parameters

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

getCameras

  • getCameras(callback: function): void
  • Enumerates Video Input Devices

    This method enumerates the available video input devices, such as cameras.

    If this method succeeds, the SDK returns a list of video input devices in an array of MediaDeviceInfo objects.

    Parameters

    Returns void

getConnectionState

  • getConnectionState(): string
  • Gets the Connection State

    This method returns the state of the connection between the SDK and Agora's edge server.

    Returns string

    The connection state:

    • DISCONNECTED: The SDK is disconnected from Agora's edge server.
    • CONNECTING: The SDK is connecting to Agora's edge server. The SDK enters this state when calling Client.join or reconnecting to Agora's edge server automatically after the connection is lost.
    • CONNECTED: The SDK is connected to Agora's edge server and joins a channel. You can now publish or subscribe to a stream in the channel.
    • DISCONNECTING: The SDK is disconnecting from Agora's edge server. The SDK enters this state when calling Client.leave.

getLocalAudioStats

  • getLocalAudioStats(callback: function): void
  • Retrieves the Audio Statistics of the Local Stream

    This method retrieves the audio statistics of the published stream, including audio codec type, sampling rate, bitrate, and so on.

    Note:

    • Some of the statistics are calculated after the stream-published event, which may take at most 3 seconds.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getLocalAudioStats((localAudioStats) => {
        for(var uid in localAudioStats){
             console.log(`Audio CodecType from ${uid}: ${localAudioStats[uid].CodecType}`);
             console.log(`Audio MuteState from ${uid}: ${localAudioStats[uid].MuteState}`);
             console.log(`Audio RecordingLevel from ${uid}: ${localAudioStats[uid].RecordingLevel}`);
             console.log(`Audio SamplingRate from ${uid}: ${localAudioStats[uid].SamplingRate}`);
             console.log(`Audio SendBitrate from ${uid}: ${localAudioStats[uid].SendBitrate}`);
             console.log(`Audio SendLevel from ${uid}: ${localAudioStats[uid].SendLevel}`);
        }
    });

    Parameters

    Returns void

getLocalVideoStats

  • getLocalVideoStats(callback: function): void
  • Retrieves the Video Statistics of the Local Stream

    This method retrieves the video statistics of the published stream, including video resolution, bitrate, frame rate, and so on.

    Note:

    • Some of the statistics are calculated after the stream-published event, which may take at most 3 seconds.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getLocalVideoStats((localVideoStats) => {
        for(var uid in localVideoStats){
             console.log(`Video CaptureFrameRate from ${uid}: ${localVideoStats[uid].CaptureFrameRate}`);
             console.log(`Video CaptureResolutionHeight from ${uid}: ${localVideoStats[uid].CaptureResolutionHeight}`);
             console.log(`Video CaptureResolutionWidth from ${uid}: ${localVideoStats[uid].CaptureResolutionWidth}`);
             console.log(`Video EncodeDelay from ${uid}: ${localVideoStats[uid].EncodeDelay}`);
             console.log(`Video MuteState from ${uid}: ${localVideoStats[uid].MuteState}`);
             console.log(`Video SendBitrate from ${uid}: ${localVideoStats[uid].SendBitrate}`);
             console.log(`Video SendFrameRate from ${uid}: ${localVideoStats[uid].SendFrameRate}`);
             console.log(`Video SendResolutionHeight from ${uid}: ${localVideoStats[uid].SendResolutionHeight}`);
             console.log(`Video SendResolutionWidth from ${uid}: ${localVideoStats[uid].SendResolutionWidth}`);
             console.log(`Video TargetSendBitrate from ${uid}: ${localVideoStats[uid].TargetSendBitrate}`);
             console.log(`Video TotalDuration from ${uid}: ${localVideoStats[uid].TotalDuration}`);
             console.log(`Video TotalFreezeTime from ${uid}: ${localVideoStats[uid].TotalFreezeTime}`);
        }
    });

    Parameters

    Returns void

getNetworkStats

  • getNetworkStats(callback: function): void
  • Gets the Statistics of the System Network

    DEPRECATED from v2.5.1, use getTransportStats instead.

    This method gets the statistics of the browser's local network.

    Currently only the network type information is provided, see NetworkType.

    Note:

    Chrome 61+ is required for this function, and the compatibility is not guaranteed. See Network Information API for details.

    example

    Sample Code

    client.getNetworkStats((stats) => {
        console.log(`Current network type: ${stats.NetworkType}`);
    });

    Parameters

    • callback: function

      The callback contains the statistics of the system network.

    Returns void

getPlayoutDevices

  • getPlayoutDevices(callback: function): void
  • Enumerates Audio Output Devices

    This method enumerates the available audio output devices, such as speakers.

    If this method succeeds, the SDK returns a list of audio output devices in an array of MediaDeviceInfo objects.

    Parameters

    Returns void

getRecordingDevices

  • getRecordingDevices(callback: function): void
  • Enumerates Audio Input Devices

    This method enumerates the available audio input devices, such as microphones.

    If this method succeeds, the SDK returns a list of audio input devices in an array of MediaDeviceInfo objects.

    Parameters

    Returns void

getRemoteAudioStats

  • getRemoteAudioStats(callback: function): void
  • Retrieves the Audio Statistics of the Remote Stream

    This method retrieves the audio statistics of the remote stream, including audio codec type, packet loss rate, bitrate, and so on.

    Note:

    • The statistics are calculated after the stream-subscribed event, which may take at most 3 seconds.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getRemoteAudioStats((remoteAudioStatsMap) => {
        for(var uid in remoteAudioStatsMap){
             console.log(`Audio CodecType from ${uid}: ${remoteAudioStatsMap[uid].CodecType}`);
             console.log(`Audio End2EndDelay from ${uid}: ${remoteAudioStatsMap[uid].End2EndDelay}`);
             console.log(`Audio MuteState from ${uid}: ${remoteAudioStatsMap[uid].MuteState}`);
             console.log(`Audio PacketLossRate from ${uid}: ${remoteAudioStatsMap[uid].PacketLossRate}`);
             console.log(`Audio RecvBitrate from ${uid}: ${remoteAudioStatsMap[uid].RecvBitrate}`);
             console.log(`Audio RecvLevel from ${uid}: ${remoteAudioStatsMap[uid].RecvLevel}`);
             console.log(`Audio TotalFreezeTime from ${uid}: ${remoteAudioStatsMap[uid].TotalFreezeTime}`);
             console.log(`Audio TotalPlayDuration from ${uid}: ${remoteAudioStatsMap[uid].TotalPlayDuration}`);
             console.log(`Audio TransportDelay from ${uid}: ${remoteAudioStatsMap[uid].TransportDelay}`);
        }
    });

    Parameters

    Returns void

getRemoteVideoStats

  • getRemoteVideoStats(callback: function): void
  • Retrieves the Video Statistics of the Remote Stream

    This method retrieves the video statistics of the remote stream, including packet loss rate, video bitrate, frame rate, and so on.

    Note:

    • The statistics are calculated after the stream-subscribed event, which may take at most 3 seconds.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getRemoteVideoStats((remoteVideoStatsMap) => {
        for(var uid in remoteVideoStatsMap){
             console.log(`Video End2EndDelay from ${uid}: ${remoteVideoStatsMap[uid].End2EndDelay}`);
             console.log(`Video MuteState from ${uid}: ${remoteVideoStatsMap[uid].MuteState}`);
             console.log(`Video PacketLossRate from ${uid}: ${remoteVideoStatsMap[uid].PacketLossRate}`);
             console.log(`Video RecvBitrate from ${uid}: ${remoteVideoStatsMap[uid].RecvBitrate}`);
             console.log(`Video RecvResolutionHeight from ${uid}: ${remoteVideoStatsMap[uid].RecvResolutionHeight}`);
             console.log(`Video RecvResolutionWidth from ${uid}: ${remoteVideoStatsMap[uid].RecvResolutionWidth}`);
             console.log(`Video RenderFrameRate from ${uid}: ${remoteVideoStatsMap[uid].RenderFrameRate}`);
             console.log(`Video RenderResolutionHeight from ${uid}: ${remoteVideoStatsMap[uid].RenderResolutionHeight}`);
             console.log(`Video RenderResolutionWidth from ${uid}: ${remoteVideoStatsMap[uid].RenderResolutionWidth}`);
             console.log(`Video TotalFreezeTime from ${uid}: ${remoteVideoStatsMap[uid].TotalFreezeTime}`);
             console.log(`Video TotalPlayDuration from ${uid}: ${remoteVideoStatsMap[uid].TotalPlayDuration}`);
             console.log(`Video TransportDelay from ${uid}: ${remoteVideoStatsMap[uid].TransportDelay}`);
        }
    });

    Parameters

    Returns void

getSessionStats

  • getSessionStats(callback: function): void
  • Gets the Statistics of the Session

    This method gets the statistics of the session connection.

    Note:

    • This method should be called after joining the channel, and it may take at most 3 seconds to retrieve the statistics.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getSessionStats((stats) => {
        console.log(`Current Session Duration: ${stats.Duration}`);
        console.log(`Current Session UserCount: ${stats.UserCount}`);
        console.log(`Current Session SendBytes: ${stats.SendBytes}`);
        console.log(`Current Session RecvBytes: ${stats.RecvBytes}`);
        console.log(`Current Session SendBitrate: ${stats.SendBitrate}`);
        console.log(`Current Session RecvBitrate: ${stats.RecvBitrate}`);
    });

    Parameters

    • callback: function

      The callback contains the statistics of the session connection.

    Returns void

getSystemStats

  • getSystemStats(callback: function): void
  • Gets the Statistics of the System

    This method gets the statistics of the system.

    Currently only the battery level information is provided, see BatteryLevel.

    Note:

    This feature is experimental, see Battery Status API for browser compatibility.

    example

    Sample Code

    client.getSystemStats((stats) => {
        console.log(`Current battery level: ${stats.BatteryLevel}`);
    });

    Parameters

    • callback: function

      The callback contains the statistics of the system.

    Returns void

getTransportStats

  • getTransportStats(callback: function): void
  • Gets the Statistics of the Transmission

    This method gets the statistics of the transmission quality to Agora service.

    Note:

    • Calculation of the statistics may take at most 3 seconds.
    • This method supports the Chrome browser only.
    example

    Sample Code

    client.getTransportStats((stats) => {
        console.log(`Current Transport RTT: ${stats.RTT}`);
        console.log(`Current Network Type: ${stats.networkType}`);
        console.log(`Current Transport OutgoingAvailableBandwidth: ${stats.OutgoingAvailableBandwidth}`);
    });

    Parameters

    • callback: function

      The callback contains the statistics of the transmission quality.

    Returns void

init

  • init(appId: string, onSuccess?: function, onFailure?: function): void
  • Initializes a Client Object

    This method initializes the client object.

    example

    Sample Code

    client.init(appId, function() {
        console.log("client initialized");
        // Join a channel
        //……
    }, function(err) {
        console.log("client init failed ", err);
        // Error handling
    });

    Parameters

    • appId: string

      Pass in the App ID for your project. ASCII characters only, and the string length must be 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

join

  • join(tokenOrKey: string | null, channel: string, uid: number | string | null, onSuccess?: function, onFailure?: function): void
  • Joins an AgoraRTC Channel

    This method joins an AgoraRTC channel.

    example

    Sample Code

    client.join(<token>, "1024", null, function(uid) {
        console.log("client" + uid + "joined channel");
        // Create a local stream
        //……
    }, function(err) {
        console.error("client join failed ", err);
        // Error handling
    });

    Parameters

    • tokenOrKey: string | null
      • Low security requirements: Pass null as the parameter value.
      • High security requirements: Pass the string of the Token or Channel Key as the parameter value. See Use Security Keys for details.
    • channel: string

      A string that provides a unique channel name for the Agora session. The length must be within 64 bytes. Supported character scopes:

      • 26 lowercase English letters a-z
      • 26 uppercase English letters A-Z
      • 10 numbers 0-9
      • Space
      • "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", "{", "}", "|", "~", ","
    • uid: number | string | null

      The user ID, an integer or a string, ASCII characters only. Ensure this ID is unique. If you set the uid to null, the server assigns one and returns it in the onSuccess callback.

      Note:

      • All users in the same channel should have the same type (number or string) of uid.
      • If you use a number as the user ID, it should be a 32-bit unsigned integer with a value ranging from 0 to (232-1).
      • If you use a string as the user ID, the maximum length is 255 characters.
    • Optional onSuccess: function

      The callback when the method succeeds. The server returns the uid which represents the identity of the user.

        • (uid: number | string): void
        • Parameters

          • uid: number | string

          Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

leave

  • leave(onSuccess?: function, onFailure?: function): void
  • Leaves an AgoraRTC Channel

    This method enables a user to leave a channel.

    example

    Sample Code

    client.leave(function() {
        console.log("client leaves channel");
        //……
    }, function(err) {
        console.log("client leave 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: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

on

  • on(event: "stream-published", callback: function): void
  • on(event: "stream-added", callback: function): void
  • on(event: "stream-removed", callback: function): void
  • on(event: "stream-subscribed", callback: function): void
  • on(event: "peer-leave", callback: function): void
  • on(event: "mute-audio", callback: function): void
  • on(event: "unmute-audio", callback: function): void
  • on(event: "mute-video", callback: function): void
  • on(event: "unmute-video", callback: function): void
  • on(event: "client-banned", callback: function): void
  • on(event: "active-speaker", callback: function): void
  • on(event: "volume-indicator", callback: function): void
  • on(event: "liveStreamingStarted", callback: function): void
  • on(event: "liveStreamingFailed", callback: function): void
  • on(event: "liveStreamingStopped", callback: function): void
  • on(event: "liveTranscodingUpdated", callback: function): void
  • on(event: "streamInjectedStatus", callback: function): void
  • on(event: "onTokenPrivilegeWillExpire", callback: function): void
  • on(event: "onTokenPrivilegeDidExpire", callback: function): void
  • on(event: "error", callback: function): void
  • on(event: "network-type-changed", callback: function): void
  • on(event: "recording-device-changed", callback: function): void
  • on(event: "playout-device-changed", callback: function): void
  • on(event: "camera-changed", callback: function): void
  • on(event: "stream-type-changed", callback: function): void
  • on(event: "connection-state-change", callback: function): void
  • on(event: "stream-reconnect-start", callback: function): void
  • on(event: "stream-reconnect-end", callback: function): void
  • on(event: "client-role-changed", callback: function): void
  • on(event: "peer-online", callback: function): void
  • on(event: "network-quality", callback: function): void
  • on(event: "stream-fallback", callback: function): void
  • on(event: "stream-updated", callback: function): void
  • on(event: "exception", callback: function): void
  • Occurs when the local stream is published.

    example

    Sample Code

    client.on("stream-published", function(evt) {
        console.log("local stream published");
        //……
    })
    

    Parameters

    • event: "stream-published"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the remote stream is added.

    example

    Sample Code

    client.on("stream-added", function(evt) {
        var stream = evt.stream;
        console.log("new stream added ", stream.getId());
        // Subscribe the stream.
        //……
    })
    

    Parameters

    • event: "stream-added"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the remote stream is removed; for example, a peer user calls Client.unpublish.

    example

    Sample Code

    client.on("stream-removed", function(evt) {
        var stream = evt.stream;
        console.log("remote stream was removed", stream.getId());
        //……
    });
    

    Parameters

    • event: "stream-removed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when a user subscribes to a remote stream.

    example

    Sample Code

    client.on("stream-subscribed", function(evt) {
        var stream = evt.stream;
        console.log("new stream subscribed ", stream.getId());
        // Play the stream.
        //……
    })
    

    Parameters

    • event: "stream-subscribed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the peer user leaves the channel; for example, the peer user calls Client.leave.

    example

    Sample Code

    client.on("peer-leave", function(evt) {
        var uid = evt.uid;
        console.log("remote user left ", uid);
        //……
    });
    

    Parameters

    • event: "peer-leave"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the peer user mutes the audio.

    example

    Sample Code

    client.on("mute-audio", function(evt) {
      var uid = evt.uid;
      console.log("mute audio:" + uid);
      //alert("mute audio:" + uid);
    });
    

    Parameters

    • event: "mute-audio"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the peer user unmutes the audio.

    example

    Sample Code

    client.on("unmute-audio", function (evt) {
      var uid = evt.uid;
      console.log("unmute audio:" + uid);
    });
    

    Parameters

    • event: "unmute-audio"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the peer user turns off the video.

    example

    Sample Code

    client.on("mute-video", function (evt) {
      var uid = evt.uid;
      console.log("mute video" + uid);
      //alert("mute video:" + uid);
    })
    

    Parameters

    • event: "mute-video"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the peer user turns on the video.

    example

    Sample Code

    client.on("unmute-video", function (evt) {
      var uid = evt.uid;
      console.log("unmute video:" + uid);
    })
    

    Parameters

    • event: "unmute-video"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • This callback notifies the peer user that he/she is banned from the channel. Only the banned users receive this callback.

    example

    Sample Code

    client.on("client-banned", function (evt) {
       var uid = evt.uid;
       var attr = evt.attr;
       console.log(" user banned:" + uid + ", bantype:" + attr);
       alert(" user banned:" + uid + ", bantype:" + attr);
    });
    

    Parameters

    • event: "client-banned"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • This callback notifies the application who is the active speaker in the channel.

    example

    Sample Code

    client.on("active-speaker", function(evt) {
         var uid = evt.uid;
         console.log("update active speaker: client " + uid);
      });
    

    Parameters

    • event: "active-speaker"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • This callback notifies the application of all the speaking remote users and their volumes.

    It is disabled by default. You can enable this event by calling enableAudioVolumeIndicator. If enabled, it reports the volumes every two seconds regardless of whether there are users speaking.

    The volume is an integer ranging from 0 to 100. Usually a user with volume above five will be counted as a speaking user.

    example

    Sample Code

    client.on("volume-indicator", function(evt){
        evt.attr.forEach(function(volume, index){
        console.log(`#{index} UID ${volume.uid} Level ${volume.level}`);
      });
    });

    Parameters

    • event: "volume-indicator"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the live streaming starts.

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the live streaming fails.

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the live streaming stops.

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the live transcoding setting is updated.

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the injected online media stream's status is updated.

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the Token expires in 30 seconds.

    You should request a new Token from your server and call Client.renewToken.

    example

    Sample Code

    client.on("onTokenPrivilegeWillExpire", function(){
      //After requesting a new token
      client.renewToken(token);
    });
    

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the Token expires.

    You should request a new Token from your server and call Client.renewToken.

    example

    Sample Code

    client.on("onTokenPrivilegeDidExpire", function(){
      //After requesting a new token
      client.renewToken(token);
    });
    

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when an error message is reported and requires error handling.

    example

    Sample Code

    client.on("error", function(err) {
        console.log("Got error msg:", err.reason);
      });
    

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the network type changes.

    example

    Sample Code

    client.on("network-type-changed", function(evt) {
        console.log("Network Type Changed to", evt.networkType);
      });
    

    Note:

    Chrome 61+ is required for this function, and the compatibility is not guaranteed. See Network Information API for details.

    Parameters

    • event: "network-type-changed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when an audio input device is added or removed.

    example

    Sample Code

    client.on("recording-device-changed", function(evt) {
        console.log("Recording Device Changed", evt.state, evt.device);
      });
    

    Parameters

    • event: "recording-device-changed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when an audio output device is added or removed.

    example

    Sample Code

    client.on("playout-device-changed", function(evt) {
        console.log("Playout Device Changed", evt.state, evt.device);
      });
    

    Note:

    Only supports Chrome 49+.

    Parameters

    • event: "playout-device-changed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when a camera is added or removed.

    example

    Sample Code

    client.on("camera-changed", function(evt) {
        console.log("Camera Changed", evt.state, evt.device);
      });
    

    Parameters

    • event: "camera-changed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the type of a video stream changes.

    It happens when a high-video stream changes to a low-video stream, or vice versa.

    The stream type (streamType):

    • 0: High-bitrate, high-resolution video stream.
    • 1: Low-bitrate, low-resolution video stream.
    example

    Sample Code

    client.on("stream-type-changed", function(evt) {
        console.log("Stream Type Change", evt.uid, evt.streamType);
      });
    

    Parameters

    • event: "stream-type-changed"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the network connection state changes.

    The connection between the SDK and Agora's edge server has the following states:

    • DISCONNECTED: The SDK is disconnected from Agora's edge server.
    • CONNECTING: The SDK is connecting to Agora's edge server. The SDK enters this state when calling Client.join or reconnecting to Agora's edge server automatically after the connection is lost.
    • CONNECTED: The SDK is connected to Agora's edge server and joins a channel. You can now publish or subscribe to a stream in the channel. If the connection is lost because, for example, the network is down or switched, the SDK triggers this callback and notifies the app that the state changes from CONNECTED to CONNECTING.
    • DISCONNECTING: The SDK is disconnecting from Agora's edge server. The SDK enters this state when calling Client.leave.
    example

    Sample Code

    client.on("connection-state-change", function(evt) {
      console.log(evt.prevState, evt.curState);
    })

    Parameters

    • event: "connection-state-change"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • curState: string

              The current connection state.

            • prevState: string

              The previous connection state.

          Returns void

    Returns void

  • Occurs when the SDK starts republishing or re-subscribing to a stream.

    example

    Sample Code

    client.on("stream-reconnect-start", function(evt) {
      console.log(evt.uid);
    })

    Parameters

    • event: "stream-reconnect-start"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • uid: number | string

              The corresponding uid of the stream being republished or re-subscribed to.

          Returns void

    Returns void

  • Occurs when the SDK finishes republishing or re-subscribing to a stream.

    example

    Sample Code

    client.on('stream-reconnect-end', function(evt) {
      console.log(evt.uid, evt.success, evt.reason);
    })

    Parameters

    • event: "stream-reconnect-end"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • reason: string
              • An empty string if success is true.
              • The failure reason if success is false.
            • success: boolean

              The result of republishing or re-subscribing to the stream.

              • true: Success.
              • false: Failure.
            • uid: number | string

              The corresponding uid of the stream being republished or re-subscribed to.

          Returns void

    Returns void

  • Occurs when the user role switches in a live broadcast. For example, from a host to an audience or vice versa.

    example

    Sample Code

    client.on('client-role-changed', function(evt) {
      console.log('client-role-changed', evt.role);
    });

    Parameters

    • event: "client-role-changed"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • role: string

              Role that the user switches to.

          Returns void

    Returns void

  • Occurs when a remote user or host joins the channel.

    • Communication channel (rtc mode): This callback notifies the app that another user joins the channel. If other users are already in the channel, the SDK also reports to the app on the existing users.
    • Live-broadcast channel (live mode): This callback notifies the app that the host joins the channel. If other hosts are already in the channel, the SDK also reports to the app on the existing hosts. Agora recommends limiting the number of hosts to 17.
    example

    Sample Code

    client.on('peer-online', function(evt) {
      console.log('peer-online', evt.uid);
    });

    Parameters

    • event: "peer-online"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • uid: string

              ID of the user or host who joins the channel.

          Returns void

    Returns void

  • Reports the network quality of the local user once every two seconds.

    This callback reports on the uplink and downlink network conditions of the local user.

    Note:

    This is an experimental feature and the network quality rating is for reference only.

    example

    Sample Code

    client.on('network-quality', function(stats) {
        console.log('downlinkNetworkQuality', stats.downlinkNetworkQuality);
        console.log('uplinkNetworkQuality', stats.uplinkNetworkQuality);
    });

    Parameters

    Returns void

  • Occurs when the remote video stream falls back to an audio-only stream due to unreliable network conditions or switches back to the video after the network conditions improve.

    If you set fallbackType as 2 in setStreamFallbackOption, the SDK triggers this callback when the remote media stream falls back to audio only due to unreliable network conditions or switches back to the video after the network condition improves.

    Note:

    Once the remote media stream is switched to the low stream due to unreliable network conditions, you can monitor the stream switch between a high stream and low stream in the stream-type-changed callback.

    Parameters

    • event: "stream-fallback"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • attr: number

              Whether the remote media stream falls back to audio-only or switches back to the video:

              • 1: the remote media stream falls back to audio-only due to unreliable network conditions.
              • 0: the remote media stream switches back to the video stream after the network conditions improve.
            • uid: string | number

              ID of the remote user sending the stream.

          Returns void

    Returns void

  • Occurs when a remote stream adds or removes a track.

    When a remote stream calls the addTrack or removeTrack method, the SDK triggers this callback.

    Parameters

    • event: "stream-updated"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • stream: Stream

              The stream that adds or removes a track:

              • video: boolean, marks whether the stream contains a video track.
              • audio: boolean, marks whether the stream contains an audio track.

          Returns void

    Returns void

  • Reports exception events in the channel.

    Exceptions are not errors, but usually mean quality issues.

    This callback also reports recovery from an exception.

    Each exception event has a corresponding recovery event, see the table below for details:

    Note:

    This callback supports only the Chrome browser.

    example

    Sample Code

    client.on("exception", function(evt) {
      console.log(evt.code, evt.msg, evt.uid);
    })

    Parameters

    • event: "exception"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • code: number

              Event code.

            • msg: string

              Event message.

            • uid: string

              The uid of the user who experiences the exception or recovery event.

          Returns void

    Returns void

publish

  • publish(stream: Stream, onFailure?: function): void
  • Publishes a Local Stream

    This method publishes a local stream to the SD-RTN.

    Note:

    In a live broadcast, whoever calls this API is the host.

    example

    Sample Code

    client.publish(stream, function(err) {
        console.log(err);
        //……
    })

    Parameters

    • stream: Stream

      Stream object, which represents the local stream.

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

removeInjectStreamUrl

  • removeInjectStreamUrl(url: string): void
  • Removes the Injected Stream

    This method removes the HTTP/HTTPS URL address (added by addInjectStreamUrl) from the live broadcast.

    Parameters

    • url: string

      URL address of the live streaming. ASCII characters only, and the string length must be greater that 0 and less than 256 bytes.

    Returns void

renewChannelKey

  • renewChannelKey(key: string, onSuccess?: function, onFailure?: function): void
  • Renews the Channel Key

    This method renews your channel key.

    Once the Channel Key schema is enabled, the key expires after a certain period of time. When the onFailure callback reports the error DYNAMIC_KEY_TIMEOUT, the application should renew the Channel Key by calling this method. Not doing so will result in SDK disconnecting with the server.

    Parameters

    • key: string

      Specifies the renewed Channel Key.

    • Optional onSuccess: function

      The callback when the method succeeds.

        • (): void
        • Returns void

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

renewToken

  • renewToken(token: string): void
  • Renews the Token

    This method renews your token.

    Once the Token schema is enabled, the token expires after a certain period of time. In case of the onTokenPrivilegeWillExpire or onTokenPrivilegeDidExpire callback events, the application should renew the Token by calling this method. Not doing so will result in SDK disconnecting with the server.

    Parameters

    • token: string

      Specifies the renewed Token.

    Returns void

setClientRole

  • setClientRole(role: "audience" | "host", callback?: function): void
  • Sets the role of the user.

    This method is applicable only to the live mode.

    Sets the role of the user such as a host or an audience (default), before joining a channel.

    This method can be used to switch the user role after the user joins a channel.

    In live mode (mode is set as live):

    • Before joining the channel, you can call this method to set the role.

    • After joining the channel, you can call this method to switch the role:

      • When you call publish, the user role switches to host; when you call unpublish, the user role switches to audience.
      • After calling publish, if you call this method and set the user role as audience, unpublish is called automatically.

    Note

    In communication mode (mode set as rtc), this method does not take effect. All users are host by default.

    example

    Sample Code

    client.setClientRole('host', function() {
      console.log("setHost success");
    }, function(e) {
      console.log("setHost failed", e);
    })

    Parameters

    • role: "audience" | "host"

      User role in a live broadcast:

      • "audience": Audience, the default role. An audience can only receive streams.
      • "host": Host. A host can both send and receive streams.
    • Optional callback: function
        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

setEncryptionMode

  • setEncryptionMode(encryptionMode: "aes-128-xts" | "aes-256-xts" | "aes-128-ecb"): void
  • Sets the Encryption Mode

    This method sets the encryption mode.

    Note:

    Ensure that you call this API before Client.join.

    example

    client.setEncryptionMode(encryptionMode);

    Parameters

    • encryptionMode: "aes-128-xts" | "aes-256-xts" | "aes-128-ecb"

      The encryption mode:

      • aes-128-xts: Sets the encryption mode as AES128XTS.
      • aes-256-xts: Sets the encryption mode as AES256XTS.
      • aes-128-ecb: Sets the encryption mode as AES128ECB.

    Returns void

setEncryptionSecret

  • setEncryptionSecret(password: string): void
  • Enables Built-in Encryption

    This method enables the built-in encryption.

    Note:

    Ensure that you call this API before Client.join.

    example

    client.setEncryptionSecret(password)

    Parameters

    • password: string

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

    Returns void

setLiveTranscoding

setLowStreamParameter

  • setLowStreamParameter(param: object): void
  • Sets the Low-video Stream Parameter

    If you enabled the dual-stream mode by calling Client.enableDualStream, use this method to set the low-video stream profile.

    If you do not set the low-video stream profile, the SDK will assign default values based on your stream video profile.

    Note:

    • As different web browsers have different restrictions on the video profile, the parameters you set may fail to take effect. The Firefox browser has a fixed frame rate of 30 fps, therefore the frame rate settings do not work on the Firefox browser.
    • 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.
    • Call Client.join before using this method.
    • Screen sharing supports the high-video stream only.

    Parameters

    • param: object

      Sets the video profile of the low-video stream.

      • Optional bitrate?: number

        Bitrate of the low-video stream frame in Kbps. A positive integer, and the value range is [1,10000000].

      • Optional framerate?: number

        Frame rate of the low-video stream frame in fps. A positive integer, and the value range is [1,10000].

      • Optional height?: number

        Height of the low-video stream frame. A positive integer, and the value range is [1,10000].

        The width and height parameters are bound together, and take effect only when both are set. Otherwise, the SDK assigns default values.

      • Optional width?: number

        Width of the low-video stream frame. A positive integer, and the value range is [1,10000].

        The width and height parameters are bound together, and take effect only when both are set.Otherwise, the SDK assigns default values.

    Returns void

setProxyServer

  • setProxyServer(proxyServer: string): void
  • Deploys the Nginx Server

    Use this method to deploy the Nginx server.

    Note:

    • Ensure that you call this API before Client.join.
    • Proxy services by different service providers may result in slow performance if you are using the Firefox browser. Therefore, Agora recommends using the same service provider for the proxy services. If you use different service providers, Agora recommends not using the Firefox browser.
    example

    client.setProxyServer(proxyServer);

    Parameters

    • proxyServer: string

      Your Nginx server domain name. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

    Returns void

setRemoteVideoStreamType

  • setRemoteVideoStreamType(stream: Stream, streamType: 0 | 1): void
  • Sets the Remote Video-stream Type

    When a remote user sends dual streams, this method decides on which stream to receive on the subscriber side. If this method is not used, the subscriber receives the high-video stream.

    example

    Sample Code

    switchStream = function (){
      if (highOrLow === 0) {
        highOrLow = 1
        console.log("Set to low");
      }
      else {
        highOrLow = 0
        console.log("Set to high");
      }
    
      client.setRemoteVideoStreamType(stream, highOrLow);
    }

    Note:

    As not all web browsers are compatible with dual streams, Agora does not recommend developers setting the resolution of the low-video stream.

    Some web browsers may not be fully compatible with dual streams:

    Browser Possible problem
    Safari on MacOS A high-video stream and a low-video stream share the same frame rate and resolution.
    Firefox A low-video stream has a fixed frame rate of 30 fps.
    Safari on iOS Safari 11 does not support switching between the two video streams.

    Parameters

    • stream: Stream

      The remote video stream object.

    • streamType: 0 | 1

      Sets the remote video stream type. The following lists the video-stream types:

      • 0: High-bitrate, high-resolution video stream.
      • 1: Low-bitrate, low-resolution video stream.

    Returns void

setStreamFallbackOption

  • setStreamFallbackOption(stream: Stream, fallbackType: 0 | 1 | 2): void
  • Sets Stream Fallback Option

    Use this method to set stream fallback option on the receiver.

    Under poor network conditions, the SDK can choose to subscribe to the low-video stream or only the audio stream.

    Note:

    This method can only be used when the publisher has enabled the dual-stream mode by enableDualStream.

    example

    Sample Code

    // The sender side, after publishing the high stream
    client.enableDualStream();
    
    // The receiver side, set the fallback option as 2
    client.setStreamFallbackOption(remoteStream, 2);

    Parameters

    • stream: Stream

      The remote stream object.

    • fallbackType: 0 | 1 | 2

      The fallback option:

      • 0: Disable the fallback.
      • 1: (Default) Automatically subscribe to the low-video stream under poor network.
      • 2: Under poor network, the SDK may subscribe to the low-video stream (of lower resolution and lower bitrate) first, but if the network still does not allow displaying the video, the SDK will receive audio only.

    Returns void

setTurnServer

  • setTurnServer(turnServer: object): void
  • Deploys the TURN Server

    Use this method to deploy the TURN server.

    Note:

    Ensure that you call this API before Client.join.

    example

    client.setTurnServer(config);

    Parameters

    • turnServer: object

      The TURN server settings.

      • Optional forceturn?: boolean

        Sets whether to force data transfer by TURN Server:

        • true: Force data transfer.
        • false: (default) Not to force data transfer.
      • password: string

        Your TURN Server password. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

      • Optional tcpport?: string

        The TCP port(s) you want add to TURN Server. Numeric characters only, and the string length must be greater than 0 and less than 256 bytes.

      • turnServerURL: string

        Your TURN Server URL address. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

      • udpport: string

        The UDP port(s) you want to add to TURN Server. Numeric characters only, and the string length must be greater than 0 and less than 256 bytes.

      • username: string

        Your TURN Server username. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

    Returns void

startLiveStreaming

  • startLiveStreaming(url: string, enableTranscoding?: boolean): void
  • Starts a Live Stream

    This method starts a live stream.

    example

    Sample Code

    client.setLiveTranscoding(<coding>);
    client.startLiveStreaming(<url>, true)

    Note:

    Call startLiveStreaming after createStream. For details, see Push Streams to the CDN.

    Parameters

    • url: string

      URL address for the live stream. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

    • Optional enableTranscoding: boolean

      Marks whether to enable live transcoding. If set as true, setLiveTranscoding must be called before this method.

    Returns void

stopLiveStreaming

  • stopLiveStreaming(url: string): void
  • Stops Live Streaming

    This method stops and deletes the live streaming.

    Parameters

    • url: string

      URL address of the live streaming. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes.

    Returns void

subscribe

  • subscribe(stream: Stream, options?: object, onFailure?: function): void
  • Subscribes to a Remote Stream

    This method enables a user to subscribe to a remote stream.

    example

    Sample Code

    client.subscribe(stream, function(err) {
        console.error("stream subscribe failed", err);
        //……
    });

    Advanced

    This method can be called multiple times for a single remote stream, and enables you to switch between receiving/not receiving the video or audio data flexibly.

    example

    Sample Code

    // Initially, subscribe to the stream and receive only the video data
    client.subscribe(stream, {video: true, audio: false});
    
    // After a while, switch to receiving only the audio data
    client.subscribe(stream, {video: false, audio: true});

    Parameters

    • stream: Stream

      Stream object, which represents the remote stream.

    • Optional options: object

      Sets whether to receive the video or audio data independently by the video and audio parameters.

      Note:

      • video and audio cannot be set as false at the same time. If you need to stop subscribing to the stream, call Client.unsubscribe instead.
      • Safari does not support independent subscription. Set options as null for Safari, otherwise theSAFARI_NOT_SUPPORTED_FOR_TRACK_SUBSCRIPTION error occurs.
      • Optional audio?: boolean

        Marks whether to receive the audio data.

        • true: (Default) Receives the audio data.
        • false: Not receives the audio data.
      • Optional video?: boolean

        Marks whether to receive the video data.

        • true: (Default) Receives the video data.
        • false: Not receives the video data.
    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

unpublish

  • unpublish(stream: Stream, onFailure?: function): void
  • Unpublishes the Local Stream

    This method unpublishes the local stream.

    example

    Sample Code

    client.unpublish(stream, function(err) {
        console.log(err);
        //……
    })
    

    Parameters

    • stream: Stream

      Stream object, which represents the local stream.

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void

unsubscribe

  • unsubscribe(stream: Stream, onFailure?: function): void
  • Unsubscribes from the Remote Stream

    This method enables the user to unsubscribe from the remote stream.

    example

    Sample Code

    client.unsubscribe(stream, function(err) {
        console.log(err);
        //……
    })
    

    Parameters

    • stream: Stream

      Stream object, which represents the remote stream.

    • Optional onFailure: function

      The callback when the method fails.

        • (err: any): void
        • Parameters

          • err: any

          Returns void

    Returns void