The Client interface provides major functions for a voice/video call, such as joining a channel and publishing a stream.

The Client object is created by the createClient method and represents the local client.

Hierarchy

  • Client

Index

Methods

addInjectStreamUrl

  • Injects an online media stream to a live interactive streaming channel.

    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. See Inject an Online Media Stream for details.

    This method call triggers the following callbacks:

    • On the local client:
      • Client.on("streamInjectedStatus"), with the state of injecting the online stream.
      • Client.on("stream-added") and Client.on("peer-online")(uid: 666), if the online media stream is injected into the channel.
    • On the remote client:
      • Client.on("stream-added") and Client.on("peer-online")(uid: 666), if the online media stream is injected into the channel.

    Note

    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 HTTP-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. The following are common errors:

      • "STILL_ON_PUBLISHING": Still publishing the stream. Disable dual streams later.
      • "DISABLE_DUALSTREAM_FAILED": Fails to disable dual streams.
        • (err: string): void
        • Parameters

          • err: string

          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 triggers the "volume-indicator" callback to report the volumes every two seconds, regardless of whether there are active speakers.

    Note

    If you have multiple tabs running the Web SDK on one device, 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 dual-stream mode on the publisher side. We recommend calling this method after joining a channel(Client.join).

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

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

    We do not recommend using the track methods (addTrack/removeTrack/replaceTrack) on dual streams, which may cause different performance in the high-quality and low-quality video streams.

    Note

    This method does not apply to the following scenarios:

    • Audio-only mode (audio: true, video: false)
    • Safari browser
    • Screen-sharing scenario
    example

    Sample code

    client.enableDualStream(function() {
      console.log("Enable 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. The following are common errors:

      • "IOS_NOT_SUPPORT": Does not support iOS.
      • "WECHAT_NOT_SUPPORT": Does not support WeChat.
      • "STILL_ON_PUBLISHING": Still publishing the stream. Enable dual streams later.
      • "ENABLE_DUALSTREAM_FAILED": Fails to enable dual streams.
        • (err: string): void
        • Parameters

          • err: string

          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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

    setInterval(() => {
      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}`);
        }
      });
    }, 1000)

    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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

    setInterval(() => {
      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}`);
        }
      });
    }, 1000)

    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.

    Note

    Only Chrome 49 or later supports this function.

    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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

    setInterval(() => {
      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}`);
        }
      });
    }, 1000)

    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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

    setInterval(() => {
      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}`);
        }
      });
    }, 1000)

    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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

    setInterval(() => {
      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}`);
      });
    }, 1000)

    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. You can call this method periodically.
    • This method supports the Chrome browser only.
    example

    Sample code

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

    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. The following are the common errors:

      • "BAD_ENVIRONMENT": Unsupported web browser.
        • (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.

    When joining the channel, the Client.on("connected") and Client.on("connection-state-change") callbacks are triggered on the local client.

    After joining the channel, if the user joining the channel is in the Communication profile, or is a host in the Live Broadcast profile, the Client.on("peer-online") callback is triggered on the remote client.

    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:

      • All lowercase English letters: a to z.
      • All uppercase English letters: A to Z.
      • All numeric characters: 0 to 9.
      • The space character.
      • Punctuation characters and other symbols, including: "!", "#", "$", "%", "&", "(", ")", "+", "-", ":", ";", "<", "=", ".", ">", "?", "@", "[", "]", "^", "_", " {", "}", "|", "~", ",".
    • 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 or 0, the server assigns one and returns it in the onSuccess callback.

    • 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. The following are common errors:

      • "INVALID_OPERATION": Unable to join the channel. Usually due to calling Client.join repeatedly.
      • "UID_CONFLICT": The uid of the local client conflicts with other users in the channel.
      • "ERR_REPEAT_JOIN": The local client has already joined the channel.
      • "SOCKET_ERROR": The SDK disconnects with the Agora server when joining the channel.
      • "CANNOT_MEET_AREA_DEMAND": The connection fails because the user is outside the chosen region for connection. For example, if you set ClientConfig.areaCode as [AgoraRTC.AREAS.EUROPE], and a user tries to join the channel in North America, this error occurs. If ClientConfig.areaCode is not explicitly set, then by default the SDK requests servers across multiple regions and chooses an optimal connection, so the console log may print this error when a user joins the channel. In this case, you can ignore the error.
        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

leave

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

    This method enables a user to leave a channel.

    When leaving the channel, the Client.on("connection-state-change") callback is triggered on the local client.

    After leaving the channel, if the user joining the channel is in the Communication profile, or is a host in the Live Broadcast profile, the Client.on("peer-leave") callback is triggered on the remote client.

    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. The following are common errors:

      • "INVALID_OPERATION": Invalid operation. Possible reasons are that this method is already called or the user is not in the channel.
      • "SOCKET_ERROR": The SDK disconnects with the Agora server when leaving the channel.
      • "LEAVE_MSG_TIMEOUT": The request to leave the channel times out. In this case, the SDK automatically disconnects and leaves the channel.
        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

off

  • off(eventType: string, callback: any): void
  • Unbinds Events

    This method removes the events attached by the Client.on() method.

    example

    Sample code

    client.on("stream-published", function processStreamPublished(evt) {
      console.log("Stream Published");
      evt.stream.play("divId");
      client.off("stream-published", processStreamPublished);
    });

    Parameters

    • eventType: string

      The event to be removed.

    • callback: any

      The function to be removed.

    Returns void

on

  • on(event: "first-audio-frame-decode", callback: function): void
  • on(event: "first-video-frame-decode", callback: function): void
  • on(event: "stream-published", callback: function): void
  • on(event: "stream-unpublished", 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-online", 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: "crypt-error", 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: "reconnect", callback: function): void
  • on(event: "connected", 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
  • on(event: "enable-local-video", callback: function): void
  • on(event: "disable-local-video", callback: function): void
  • on(event: "channel-media-relay-event", callback: function): void
  • on(event: "channel-media-relay-state", callback: function): void
  • Occurs when the first remote audio frame is decoded.

    The SDK triggers this callback when the local client successfully subscribes to a remote stream and decodes the first audio frame.

    Note This callback supports only the Google Chrome browser.

    example

    Sample code

    client.on('first-audio-frame-decode', function (evt) {
      console.log('first-audio-frame-decode');
      console.log(evt.stream);
    });

    Parameters

    • event: "first-audio-frame-decode"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns void

  • Occurs when the first remote video frame is decoded.

    The SDK triggers this callback when the local client successfully subscribes to a remote stream and decodes the first video frame.

    example

    Sample code

    client.on('first-video-frame-decode', function (evt) {
      console.log('first-video-frame-decode');
      console.log(evt.stream);
    });

    Parameters

    • event: "first-video-frame-decode"
    • callback: function
        • (evt: any): void
        • Parameters

          • evt: any

          Returns void

    Returns 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 local stream is unpublished.

    example

    Sample code

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

    Parameters

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

          • evt: any

          Returns void

    Returns void

  • Occurs when the remote stream is added.

    Note

    When the local user joins the channel, if other users are already in the channel, the SDK also reports to the app on the existing remote streams.

    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 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.

    The SDK triggers this callback under one of the following circumstances:

    • A remote user/host joins the channel by calling the Client.join method.
    • A remote user switches the user role to the host by calling the Client.setClientRole method after joining the channel.
    • A remote user/host rejoins the channel after a network interruption.
    • The host injects an online media stream into the channel by calling the Client.addInjectStreamUrl method.
    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

  • Occurs when a remote user becomes offline.

    The SDK triggers this callback in the following situations:

    • A remote user calls Client.leave and leaves the channel.
    • A remote user drops offline. When no data packet of the user or host is received for 20 seconds, the SDK assumes that the user drops offline. A poor network connection may lead to false detections, so we recommend using the signaling system for reliable offline detection.
    • A remote user switches the client role from host to audience.

    Note In live-broadcast channels, the SDK triggers this callback only when a host goes offline.

    example

    Sample code

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

    Parameters

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

          • evt: object
            • reason: string

              Reason why the user goes offline.

              • "Quit": The user calls Client.leave and leaves the channel.
              • "ServerTimeOut": The user drops offline.
              • "BecomeAudience": The client role switches from "host" to "audience".
            • uid: string

              ID of the remote user.

          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

  • Occurs when encryption or decryption fails during publishing or subscribing to a stream.

    Since
       3.0.0

    The failure is usually due to a wrong encryption password (setEncryptionSecret) or an incorrect encryption mode (setEncryptionMode).

    example

    Sample code

    client.on("crypt-error", function (evt) {
      console.log(evt.cryptType + "error!");
    });

    Parameters

    • event: "crypt-error"
    • 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.

    Usually the reason is that the UID is banned (K_UID_BANNED(14)).

    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

  • DEPRECATED from 3.0.2. Use Client.on("volume-indicator") instead.

    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.

    The SDK triggers this callback when the live transcoding setting is updated by calling the setLiveTranscoding method.

    Note

    The first call of the setLiveTranscoding method does not trigger this callback.

    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.

    Possible errors:

    • When reason is "SOCKET_DISCONNECTED", the SDK disconnects from the Agora server due to network conditions and will automatically try reconnecting.
    • If this callback reports other reasons, it means that the error occurs during the reconnecting phase.
    example

    Sample code

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

    Parameters

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

          • evt: object
            • reason: any
            • type: "error"

          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-quality video stream changes to a low-quality 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 resubscribing 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. Possible reasons:
                • REQUEST_ABORT: The republishing or resubscribing is interrupted by server reconnection. After the SDK reconnects to the server, the republishing or resubscribing resumes. You can ignore this error.
            • success: boolean

              The result of republishing or resubscribing to the stream.

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

              The corresponding uid of the stream being republished or resubscribed to.

          Returns void

    Returns void

  • Occurs when the user role switches in a live interactive streaming scenario. 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 the SDK starts reconnecting to the server automatically after the connection is lost.

    example

    Sample code

    client.on("reconnect", function() {
      console.log("reconnect");
    });

    Parameters

    • event: "reconnect"
    • callback: function
        • (): void
        • Returns void

    Returns void

  • Occurs when the SDK is connected to the server.

    example

    Sample code

    client.on("connected", function() {
      console.log("connected");
    });

    Parameters

    • event: "connected"
    • callback: function
        • (): void
        • 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

  • Occurs when a remote user of the Native SDK calls enableLocalVideo(true) to enable video capture.

    Since
       3.0.0

    Parameters

    • event: "enable-local-video"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • uid: string

              The ID of the remote user.

          Returns void

    Returns void

  • Occurs when a remote user of the Native SDK calls enableLocalVideo(false) to disable video capture.

    Since
       3.0.0

    Parameters

    • event: "disable-local-video"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • uid: string

              The ID of the remote user.

          Returns void

    Returns void

  • Reports events during the media stream relay.

    Since
       3.0.0

    Parameters

    • event: "channel-media-relay-event"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • code: number

              The event code for media stream relay.

              • 0: The user disconnects from the server due to a poor network connection.
              • 1: The user is connected to the server.
              • 2: The user joins the source channel.
              • 3: The user joins the destination channel.
              • 4: The SDK starts relaying the media stream to the destination channel.
              • 5: The server receives the video stream from the source channel.
              • 6: The server receives the audio stream from the source channel.
              • 7: The destination channel is updated.

          Returns void

    Returns void

  • Occurs when the state of the media stream relay changes.

    Since
       3.0.0

    The SDK reports the state and error code of the current media relay in this callback.

    Parameters

    • event: "channel-media-relay-state"
    • callback: function
        • (evt: object): void
        • Parameters

          • evt: object
            • code: number

              The error code.

              • 0: No error.
              • 1: An error occurs in the server response.
              • 2: No server response.
              • 3: The SDK fails to access the service, probably due to limited resources of the server.
              • 4: Fails to send the relay request.
              • 5: Fails to accept the relay request.
              • 6: The server fails to receive the media stream.
              • 7: The server fails to send the media stream.
              • 8: The SDK disconnects from the server and fails to reconnect to the server due to a poor network connection. In this case, the SDK resets the relay state. You can try startChannelMediaRelay to restart the media stream relay.
              • 9: An internal error occurs in the server.
              • 10: The token of the source channel has expired.
              • 11: The token of the destination channel has expired.
              • 12: The relay has already started. Possibly caused by calling startChannelMediaRelay repeatedly, or calling startChannelMediaRelay before stopChannelMediaRelay succeeds.
              • 13: The relay has not started. Possibly caused by calling updateChannelMediaRelay before startChannelMediaRelay succeeds.
            • state: number

              The state code.

              • 0: The SDK is initializing.
              • 1: The SDK tries to relay the media stream to the destination channel.
              • 2: The SDK successfully relays the media stream to the destination channel.
              • 3: An error occurs. See code for the error code. In case of an error, the SDK resets the media stream relay state, and you need to call startChannelMediaRelay to restart the relay.

          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.

    When the stream is published, the following callbacks are triggered:

    • On the local client: Client.on("stream-published")
    • On the remote client: Client.on("stream-added")

    Note

    In a live interactive streaming channel, 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. The following are common errors:

      • "STREAM_ALREADY_PUBLISHED": This stream object is already published.
      • "INVALID_LOCAL_STREAM": The stream object is invalid.
      • "INVALID_OPERATION": The user is not in the channel, possibly because the user has not joined the channel or the connection is interrupted.
      • "PUBLISH_STREAM_FAILED": Fails to publish the stream, usually because the connection is lost during publishing.
      • "PEERCONNECTION_FAILED": Fails to establish the media transport channel.
        • (err: string): void
        • Parameters

          • err: string

          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 interactive streaming.

    Parameters

    • url: string

      URL address of the injected stream. 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. The following are common errors:

      • "INVALID_OPERATION": The user is not in the channel. Call this method after the user joins a channel.
        • (err: string): void
        • Parameters

          • err: string

          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. When a user switches the user role after joining a channel, the following callbacks are triggered:

    • On the local client: Client.on("client-role-changed").
    • On the remote client: Client.on("peer-online") or Client.on("peer-leave").

    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(e) {
      if (!e) {
        console.log("setHost success");
      } else {
        console.log("setHost error", e);
      }
    });

    Parameters

    • role: "audience" | "host"

      User role:

      • "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?: string | null): void
        • Parameters

          • Optional err: string | null

          Returns void

    Returns void

setEncryptionMode

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

    Use this method with setEncryptionSecret method to enable the built-in encryption before joining a channel.

    All users in a channel must set the same encryption mode.

    Note

    • Ensure you call setEncryptionSecret and setEncryptionMode before joining the channel, otherwise the encryption is disabled.
    • Do not use this method for CDN live streaming.
    • If the encryption mode is incorrect, the SDK triggers the Client.on("crypt-error") callback when publishing or subscribing to a stream.
    example

    client.setEncryptionMode(encryptionMode);

    Parameters

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

      The encryption mode:

      • "aes-128-xts": 128-bit AES encryption, XTS mode.
      • "aes-256-xts": 128-bit AES encryption, ECB mode.
      • "aes-128-ecb": 256-bit AES encryption, XTS mode.
      • "sm4-128-ecb": 128-bit SM4 encryption, ECB mode.
      • "none": No encryption.

    Returns void

setEncryptionSecret

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

    Use this method with setEncryptionMode method to enable the built-in encryption before joining a channel.

    All users in a channel must set the same encryption secret.

    Note

    • Ensure you call setEncryptionSecret and setEncryptionMode before joining the channel, otherwise the encryption is disabled.
    • Do not use this method for CDN live streaming.
    • If the encryption secret is incorrect, the SDK triggers the Client.on("crypt-error") callback when publishing or subscribing to a stream.
    example

    client.setEncryptionSecret(password)

    Parameters

    • password: string

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

    Returns void

setLiveTranscoding

  • Sets Live Transcoding

    This method sets the video layout and audio for CDN live. A successful call of this method to update the transcoding settings triggers the Client.on("liveTranscodingUpdated") callback.

    Note

    Parameters

    Returns void

setLowStreamParameter

  • setLowStreamParameter(param: object): void
  • Sets the video profile of the low-quality video stream

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

    The default video profile of the low-quality video stream:

    • Resolution (width × height): 160 × 120
    • Bitrate: 50 Kbps
    • Frame rate: 15 fps

    Note

    • The low-quality video stream keeps the aspect ratio of the high-quality video stream. If the resolution of the low-quality stream has a different aspect ratio, the SDK automatically adjusts the height of the low-quality stream.
    • As different web browsers have different restrictions on the video profile, your settings may not take effect.
      • The Firefox browser has a fixed frame rate of 30 fps, therefore the frame rate setting does not work on the Firefox browser.
      • The resolution you set may not take effect.
    • Billings are calculated based on the actual resolution.
    • Call this method after calling Client.join and before calling Client.publish.

    Parameters

    • param: object

      The video profile of the low-quality video stream.

      • Optional bitrate?: number

        The bitrate of the low-quality video stream frame in Kbps.

        A positive integer, and the value range is [1,10000000]. The default value is 50.

      • Optional framerate?: number

        The frame rate of the low-quality video stream frame in fps.

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

      • Optional height?: number

        The height of the low-quality video stream frame.

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

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

      • Optional width?: number

        The width of the low-quality video stream frame.

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

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

    Returns void

setProxyServer

  • setProxyServer(proxyServer: string): void
  • Deploys a Proxy Server

    Use this method to deploy an HTTP proxy server.

    You can also use cloud proxy by startProxyServer. See Use Cloud Proxy for details.

    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 proxy server domain name. ASCII characters only, and the string length must be greater than 0 and less than 256 bytes. See ClientConfig.proxyServer for details.

    Returns void

setRemoteVideoStreamType

  • setRemoteVideoStreamType(stream: Stream, streamType: 0 | 1): void
  • Sets the stream type of a remote stream

    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-quality 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 or later 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-quality video stream or only the audio stream.

    If the auto-fallback option is enabled, the SDK triggers the Client.on("stream-type-changed") callback when the remote stream changes from a high-quality video stream to a low-quality video stream or vice versa, and triggers the Client.on("stream-fallback") callback when the remote stream changes from a video stream to an audio-only stream or vice versa.

    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-quality video stream under poor network.
      • 2: Under poor network, the SDK may subscribe to the low-quality 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

  • Deploys the TURN Server

    Use this method to deploy the TURN server.

    You can also use cloud proxy by startProxyServer. See Use Cloud Proxy for details.

    Note

    Ensure that you call this API before Client.join.

    example

    client.setTurnServer(config);

    Parameters

    • turnServer: TurnServer[]

      An array of the TurnServer objects. You can pass configurations of multiple TURN servers to this parameter.

    Returns void

startChannelMediaRelay

  • Starts relaying media streams across channels.

    Since
       3.0.0

    After this method call, the SDK triggers the following callbacks:

    • Client.on("channel-media-relay-state"), which reports the state and error code of the media stream relay.
      • If the media stream relay starts successfully, this callback returns state 2 and code 0.
      • If the media stream relay fails, this callback returns state 3. Refer to code for the error code and call this method again.
    • Client.on("channel-media-relay-event"), which reports the events of the media stream relay.
      • If the media stream relay starts successfully, this callback returns code 4, reporting that the SDK starts relaying the media stream to the destination channel.

    Note

    • Contact support@agora.io to enable this function.
    • We do not support string user IDs in this API.
    • Call this method only after joining a channel.
    • In a live-broadcast channel, only a host can call this method.
    • To call this method again after it succeeds, you must call stopChannelMediaRelay to quit the current relay.
    example

    Sample code

    client.startChannelMediaRelay(channelMediaConfig, function(e) {
      if(e) {
        utils.notification(`startChannelMediaRelay failed: ${JSON.stringify(e)}`);
      } else {
        utils.notification(`startChannelMediaRelay success`);
      }
    });

    Parameters

    Returns void

startLiveStreaming

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

    This method starts a live stream. For details, see Push Streams to the CDN.

    When the live stream starts, the SDK triggers the Client.on("liveStreamingStarted") callback. If this method call fails, the SDK triggers the Client.on("liveStreamingFailed") callback.

    Note

    • Only hosts in live-broadcast channels can call this method. Ensure that you set the user role as "host" in setClientRole.
    • Call this method after the publish method call succeeds.
    • Push one live stream at a time. If you need to push several streams, ensure that the current stream starts successfully before pushing the next one.
    example

    Sample code

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

    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

startProxyServer

  • startProxyServer(type?: number): void
  • Enables Cloud Proxy

    This method must be called before joining the channel or after leaving the channel.

    To use the cloud proxy service, some extra configurations are needed, see Use Cloud Proxy for details.

    Parameters

    • Optional type: number

    Returns void

stopChannelMediaRelay

  • stopChannelMediaRelay(callback: function): void
  • Stops the media stream relay.

    Since
       3.0.0

    Once the relay stops, the user leaves all the destination channels.

    After this method call, the SDK triggers the Client.on("channel-media-relay-state") callback.

    • If the relay stops, the callback returns state 0.
    • If the relay fails to stop, the callback returns state 3 and code 2 or 8. The failure is usually due to poor network conditions. You can call Client.leave to leave the channel and stop the relay.
    example

    Sample code

    stopChannelMediaRelay: function() {
      client.stopChannelMediaRelay(function(e) {
        if(e) {
          utils.notification(`stopChannelMediaRelay failed: ${JSON.stringify(e)}`);
        } else {
          utils.notification(`stopChannelMediaRelay success`);
        }
      });
    }

    Parameters

    Returns void

stopLiveStreaming

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

    This method stops and deletes the live streaming. When the live stream stops, the SDK triggers the Client.on("liveStreamingStopped") callback.

    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

stopProxyServer

  • stopProxyServer(): void
  • Disables Cloud Proxy

    This method must be called before joining the channel or after leaving the channel.

    This method disables all proxy settings, including those set by setProxyServer and setTurnServer.

    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.

    After the user subscribes to a remote stream, the SDK triggers the Client.on("stream-subscribed") callback. If the remote stream contains an audio track, the SDK also triggers the Client.on("first-audio-frame-decode") callback; if the remote stream contains a video track, the SDK also triggers the Client.on("first-video-frame-decode") callback.

    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. The following are common errors:

      • "SAFARI_NOT_SUPPORTED_FOR_TRACK_SUBSCRIPTION": Safari does not support independent subscription.
      • "INVALID_OPERATION": The user is not in the channel, possibly because the user has not joined the channel or the connection is interrupted.
      • "SUBSCRIBE_STREAM_FAILED": The subscription fails, usually because the SDK has disconnected from the Agora server when subscribing to the stream.
      • "PEERCONNECTION_FAILED": Fails to establish the media transport channel.
        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

unpublish

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

    This method unpublishes the local stream.

    When the stream is unpublished, the Client.on("stream-unpublished") callback is triggered on the local client, and the Client.on("stream-removed") callback is triggered on the remote client.

    Note

    In a live interactive streaming scenario, the user role of a host switches to audience after unpublishing, and the Client.on("peer-leave") callback is triggered on the remote client.

    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. The following are common errors:

      • "STREAM_NOT_YET_PUBLISHED": The specified stream object is not published.
      • "INVALID_LOCAL_STREAM": The specified stream object is invalid.
      • "INVALID_OPERATION": The user is not in the channel, possibly because the user has not joined the channel or the connection is interrupted.
        • (err: string): void
        • Parameters

          • err: string

          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. The following are common errors:

      • "INVALID_REMOTE_STREAM": The specified stream object is invalid.
      • "INVALID_OPERATION": The user is not in the channel, possibly because the user has not joined the channel or the connection is interrupted.
      • "NO_SUCH_REMOTE_STREAM": The specified stream object is not found.
      • "UNSUBSCRIBE_STREAM_FAILED": Fails to unsubscribe from the stream, usually because the SDK has disconnected from the Agora server when unsubscribing from the stream.
        • (err: string): void
        • Parameters

          • err: string

          Returns void

    Returns void

updateChannelMediaRelay

  • Updates the channels for media stream relay.

    Since
       3.0.0

    After the channel media relay starts, if you want to relay the media stream to more channels, or leave the current relay channel, you can call this method.

    After this method call, the SDK triggers the Client.on("channel-media-relay-event") callback.

    • If the update succeeds, the callback returns code 7.
    • If the update fails, the callback returns code 8, and the SDK also triggers the Client.on("channel-media-relay-state") callback with state 3. In this case, the media relay state is reset, and you need to call startChannelMediaRelay again to restart the relay.

    Note

    • Call this method after startChannelMediaRelay.
    • You can add a maximum of four destination channels to a relay.
    example

    Sample code

    client.updateChannelMediaRelay(channelMediaConfig, function(e) {
      if(e) {
        utils.notification(`updateChannelMediaRelay failed: ${JSON.stringify(e)}`);
      } else {
        utils.notification(`updateChannelMediaRelay success`);
      }
    });

    Parameters

    Returns void