Live Broadcast API - WebAgent

The Agora Native SDK for Web(WebAgent for short) library includes the following classes:

AgoraRTC Use the AgoraRTC object to create Client(s) and Stream objects.
Client Represents the web client object that provides access to core AgoraRTC functionality.
Stream Represents the local/remote media streams in a session.

AgoraRTC API Methods

Create Client Object (createRtcClient)

createRtcClient()

This method creates and returns a Client object. It should be called only once per session.

Sample code:

var client = AgoraRTC.createLiveClient();

Create Stream Object (createStream)

createStream(spec)

This method creates and returns a Stream object.

Parameter Type Description
spec Object This object contains the following properties:
streamID: represents the stream ID, normally set to uid which can be retrieved from the client.join callback.
local: represents whether the stream is local or remote, if yes, set it as true. The remote stream is created inside of the SDK, and no need to set it as false.
video: represents whether the user opens the camera. If true, then video function is enabled, which turns on the camera. If false, the video function is disabled, which doesnot turn on the camera.

Sample code:

var stream = AgoraRTC.createStream({streamID:uid, local:true, video:true});

Client API Methods and Callback Events

Represents the web client object that provides access to core AgoraRTC functionality.

Initialize Client Object (init)

init(appId, onSuccess)

This method initializes the Client object.

Parameter Type Description
appId String The App ID, a static key, is provided by Agora during registration. For users who do not have a high security requirement in most developer circumstances, the App ID should suffice.
onSuccess function (optional) the function to be called when the method succeeds.

Sample code:

client.init(appId, function() {
    log("client initialized");
    //join channel
    //……
}

Set Channel Profile (setChannelProfile)

setChannelProfile(profile, onSuccess, onFailure)

This method configures the channel profile. The Agora RtcEngine needs to know what scenario the application is in to apply different method for optimization.

The Agora Native SDK currently supports two profiles:

  • Communication

    The default setting. It is most commonly used in one-on-one conversations or meetings, where all users in the channel can talk freely.

  • Live Broadcast

    Live Broadcast has host and audience roles which can be set by calling setClientRole. The host sends and receives audio/video, while the audience only receives audio/video only with sending function disabled.

    Note

    • You cannot use both Communication and Live Broadcast profile in the same channel.
    • This method must be called and configured before user joining a channel, because the channel profile cannot be configured when the channel is in use.
Name Type Description
profile string

The channel profile. Choose from the following:

  • communication (default)
  • live-broadcasting
onSuccess function (optional) The function to be called when the method succeeds, returns the uid, which represents the identity of the user.
onFailure function (optional) the function to be called when the method fails.

Sample code:

client.setChannelProfile(profile, function(err) {
    log("client sets the channel mode");
    //……
}, function(err) {
    log("client sets channel mode failure", err);
    //error handling
});

Set User Role(setClientRole)

setClientRole(role, permissionKey, onSuccess, onFailure)

This method allows you to set the user role as a host or an audience(default) before joining a channel. This method also allows you to switch the user role after joining a channel.

Name Type Description
role String The user role in a live broadcast:
‘broadcaster’: Host
‘audience’: Audience (default)
permissionKey String

If you have not enabled the host-in authentication function, set it as NULL.

If you have enabled the host-in authentication function, depending on different user roles:

  • Audience: set it as NULL.
  • Host: set it as the In Channel Permission Key. For details, refer to Agora Keys User Guide.
onSuccess function (optional) The function to be called when the method succeeds, returns the uid, which represents the identity of the user.
onFailure function (optional) the function to be called when the method fails.

Sample code:

client.setClientRole(role, null, function(err) {
    log("client sets the user role");
    //……
}, function(err) {
    log("client fails to set the user role", err);
    //error handling
});

Enable Dual Stream Mode(enableDualStreamMode)

enableDualStreamMode(enabled, onSuccess, onFailure);

This method sets the stream mode: Single(default) or Dual Stream, which is only applicable to the live broadcast scenario.

Name Description
enabled The mode is in single stream or dual stream:
true: dual stream
false: single stream
onSuccess (optional) The function to be called when the method succeeds, returns the uid, which represents the identity of the user.
onFailure (optional) the function to be called when the method fails.

Join AgoraRTC Channel(join)

join(channelKey,channel, uid, onSuccess, onFailure)

This method allows the user to join an AgoraRTC channel.

Name Type Description
channelKey string For users who have a high security requirement, use the Channel Key, otherwise use an App ID. You can switch the use of App ID and Channel Key on Dashboard.
The Channel Key is generated according to security algorithms provided by Agora.io with an App ID and an App Certificate fetched from Dashboard.
Channel string A string providing the unique channel name for the AgoraRTC session. The length must be within 64 bytes.
The following is the supported scope: a-z,A-Z,0-9,space,! #$%&,()+, -,:;<=.,>? @[],^_,{|},~
uid integer The user ID: a 32-bit unsigned integer ranges from 1 to (2^32-1). It must be unique. If set to ‘undefined (the value is set to 0)’, the server assigns one and returns it in onSuccess callback.
onSuccess function (optional) The function to be called when the method succeeds, returns the uid, which represents the identity of the user.
onFailure function (optional) the function to be called when the method fails.

Sample code:

client.join(key,'1024', 0, function(uid) {
  log("client " + uid + "" "joined channel");
  //create local stream
  //……
}, function(err) {
  log("client join failed", err);
  //error handling
});

Renew Channel Key (renewChannelKey)

renewChannelKey(channelkey,onSuccess,onFailure)

This method allows the users to renew the Channel Key. The descriptions of the parameters are the same as above. When the error callback after calling client.init returns ERR_CHANNEL_KEY_EXPIRED = 109 or ERR_INVALID_CHANNEL_KEY = 110, your application must call this method to renew the Channel Key.

Parameter Type Description
channelkey string The Channel Key is generated according to security algorithms provided by Agora.io with an App ID and an App Certificate fetched from Dashboard.
onSuccess function (optional) The function to be called when the method succeeds returns the uid which represents the identity of the user.
onFailure function (optional) the function to be called when the method fails.

Leave AgoraRTC Channel(leave)

leave(onSuccess, onFailure)

This method allows the user to leave an AgoraRTC channel.

Parameter Type Description
onSuccess function (optional) The function to be called when the method succeeds.
onFailure function (optional) The function to be called when the method fails.

Sample code:

client.leave(function() {
    log("client leaves channel");
    //……
}, function(err) {
    log("client leave failed", err);
    //error handling
});

Publish Local Stream (publish)

publish(stream, onSuccess, onFailure)

This method publishes a local stream to the server.

Parameter Type Description
stream object Stream object, which represents the local stream.
onSuccess function The function to be called when publish local stream successfully
onFailure function (optional) The function to be called when the method fails.

Sample code:

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

Unpublish Local Stream (unpublish)

unpublish(stream, onSuccess, onFailure)

This method unpublishes the local stream.

Parameter Type Description
stream object Stream object representing local stream.
onSuccess function (optional) the function to be called when the method succeeds.
onFailure function (optional) the function to be called when the method fails.

Sample code:

client.unpublish(stream, function(err) {
    console.log("stream unpublished5.79");
}, function (err) {
    console.log("failed to unpublish stream");
});

Subscribe Remote Stream (subscribe)

subscribe(stream, onFailure)

This method subscribes remote stream from the server.

Parameter Type Description
stream object Stream object representing the remote stream.
onFailure function (optional) Function to be called when the method fails.

Sample code:

client.subscribe(stream, function(err) {
    log("stream unpublished");
    //……
})

Unsubscribe Remote Stream (unsubscribe)

unsubscribe(stream, onFailure)

This method unsubscribes the remote stream.

Parameter Type Description
stream object Stream object representing remote stream.
onFailure function (optional) The function to be called when the method fails.

Sample code:

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

Enumerate Platform Device (getDevices)

getDevices(callback)

This method enumerates platform camera/microphone devices. It is not applicable to Mac yet.

Parameter Type Description
callback Function The callback function to retrieve the devices information.
For ex. callback(devices):
devices[0].deviceId: device ID
devices[0].label: device name in string
devices[0].kind: ‘audioinput’, ‘videoinput’

Sample code:

client.getDevices (function(devices) {
var dev_count = devices.length;

var id = devices[0].deviceId;
});

Enable Built-in Encryption(setEncryptionSecret)

setEncryptionSecret(secret)

Ensure that your application calls setEncryptionSecret to specify a secret to enable the AES-128 encryption before joining a channel, otherwise the communication is unencrypted.

All users in a channel must set the same secret. The secret is automatically cleared once the user has left the channel. If the secret is not specified or set to empty, the encryption function is disabled.

Name Description
secret Encryption Password
Return Value 0: Method call succeeded.
<0: Method call failed.
client.setEncryptionSecret("1234");

Set Built-in Encryption Mode(setEncryptionMode)

setEncryptionMode (encryptionMode)

Agora Native SDK supports built-in encryption, and it is in AES-128-XTS mode by default. If you want to use other mode, call this API to set the encryption mode.

All users in the same channel must use the same encryption mode and secret. You can refer to AES encryption algorithm related information on the differences of the several encryption modes.

Note

Call setEncryptionSecret to enable the built-in encryption function before calling this API.

Name Description
encryptionMode Encryption mode. The following modes are supported currently:
“aes-128-xts”: 128-bit AES encryption, XTS mode
“aes-256-xts”: 256-bit AES encryption,XTS mode
“”: When it is set to NUL string, the encryption is in “aes-128-xts” by default.
Return Value 0: Method call succeeded.
<0: Method call failed.

Select Device (selectdevice)

selectDevice(device)

Select audio/video device to use in current session.

Parameter Type Description
device Object Device selected from device list returned by getDevices. Agora uses the selected audio/video device in the current session.

Sample code:

client.selectDevice(device);

Get Desktop Window List(getWindows)

getWindows(callback)

This method allows the users to obtain the desktop window of the operating system. The application can obtain the window list and specify the window to be shared using this method.

Parameter Type Description
callback function Use callback function to obtain the window list, for example,
callback(windows):
windows[0].windowId: window id in string
windows[0].title: window title in string

Remote Stream Added Event (stream-added)

Notifies the application that the remote stream has been added.

Sample code:

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

Remote Stream Subscribed Event (stream-subscribed)

Notifies the application that the remote stream has been subscribed, which means you can play the remote videos now.

Sample code:

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

Peer User Left Channel Event (peer-leave)

Notifies the application that the other user has left the room, (called client.leave()), which means that you can stop playing the remote video now.

Sample code:

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

Remote User Muted Video Event(peer-mute-video)

Notifies the application that the remote user has chosen not to send or to resend the local video stream.

Parameter Description
muted When muted is true, indicating the remote user has chosen not to send the local video stream, which means the other users cannot see his/her image.
When muted is false, indicating the remote user has chosen to resend the local video stream, which means the other users cannot see his/her image.

Sample code:

client.on("peer-mute-video", function (event) {

var message = event.msg;
if (message.muted) {
console.log("remote user " + message.uid + " muted video");
 } else {
console.log("remote user " + message.uid + " unmuted video");
}

Remote User Muted Audio Event(peer-mute-audio)

Notifies the application that the remote user has chosen not to send or to resend the local audio stream.

Parameter Description
muted When muted is true, indicating the remote user has chosen not to send the local audio stream, which means the other users cannot hear his/her voice.
When muted is false, indicating the remote user has chosen to resend the local audio stream, which means the other users cannot hear his/her voice.

Sample code:

client.on("peer-mute-audio", function (event) {
var message = event.msg;
if (message.muted) {
console.log("remote user " + message.uid + " muted audio");
 }

 else {
console.log("remote user " + message.uid + " unmuted audio");
}

Error Reported Event (error)

After the client object is created, any failure messages will be returned in this callback.

Sample code:

 client.on('error', function(err) {
  console.log('error from client ');
  console.log(err);

  var e = document.getElementById('agora_local');
  if (err.reason === 'ALREADY_IN_USE') {
    e.innerHTML = '<span style="color:red">Agora web call is already running<span>';
  } else if (err.reason == 'CLOSE_BEFORE_OPEN') {
    e.innerHTML = '<span>Agora Web Agent is not installed or running. Please install it from <a href="' + err.agentInstallUrl + '">here</a></span>';
  } else if (err.reason == 'INCOMPATIBLE_WEBAGENT') {
    e.innerHTML = '<span>Agora Web Agent need to be updated. Please install it from <a href="' + err.agentInstallUrl + '">here</a></span>';
  } else if (err.reason === 'LOST_CONNECTION_TO_AGENT') {
    var lost = "<div>Lost connection to Agent. Please restart agent.</div>";
    e.insertAdjacentHTML('beforeend', lost);
  } else if (err.reason === 'DYNAMIC_KEY_TIMEOUT' || err.reason === 'INVALID_DYNAMIC_KEY') {
    fetchDynamicKey(function (result) { // fetch dynamic key from backend server
      if (result.ok) {
        client.renewChannelDynamicKey(result.key, function () {
          console.log('Dynamic Key updated successfully');
        }, function (e) {
          console.log('Failed to update Dynamic Key. ' + e);
        });
      }
    });
  }
});

Stream API Methods

Initialize Local Stream Object(init)

init(onSuccess, onFailure)

This method initializes the local Stream object. No need to initialize the remote stream, because the SDK handles it internally.

Parameter Type Description
onSuccess function (optional) The function to be called when the method succeeds.
onFailure function (optional) The function to be called when an error occurs in the lifetime of client

Sample code:

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

Close Video Stream (close)

close()

This method closes the video stream,and users won’t see this video.

Play Video or Audio Stream(play)

play(elementID, onFailure)

This method plays the video or audio stream.

Parameter Type Description
elementID String html element ID
onFailure Function (optional)

Sample Code:

stream.play('div_id', function (err) {
  // stream will be played in div_id element
  console.log('failed to play stream');
});

Stop Playing Video Stream(stop)

stop()

This method stops playing the video steam on the web.

Enable Audio Stream (enableAudio)

enableAudio(callback)

This method enables the audio stream, which triggers a callback after a successful execution.

Disable Audio Stream (disableAudio)

disableAudio(callback)

This method disables the audio stream, which triggers a callback after a successful execution.

Enable Video Stream(enableVideo)

enableVideo(callback)

This method enables the video stream, which triggers a callback after a successful execution. If you receive the video steam from the user continuously, the applicable will receive the stream-added event, and the application can re-play the video.

Disable Video Stream (disableVideo)

disableVideo(callback)

This method disables the video stream, which triggers a callback after a successful execution.

Retrieve User ID (getId)

getId()

This method retrieves the stream id (the corresponding user ID).

Set Video Profile (setVideoProfile)

setVideoProfile(profile)

This method sets the video profile. Each profile corresponds to a set of video parameters, or example, resolution, frame rate, bitrate and etc. When the camera of the device does not support the specified resolution, SDK selects one suitable camera resolution automatically, but the encoder resolution still uses the one specified by setVideoProfile.

The method only sets the attributes of the streams encoded by the encoder which may be inconsistent with the final display. For example, when the resolution of the encoded stream is 640x480, and the rotation attribute of the stream is 90 degrees, then the resolution of the final display is in portrait mode.

Note

Set the video profile before calling AgoraRTC.client.join to join the channel.

The parameter profile is a json object, which includes the following attributes:

Name Enumeration Value
profile The video attribute. See the following Video Profile Definition for details.
swapWidthAndHeight Whether to swap the width and height of the stream:
true: swap
false: not swap(default)

Video Profile Definition

Video Profile (String) Enum value Resolution (width * height) Frame Rate (fps) Bitrate(kbps)
“120P” 0 160x120 15 65
“120P_3” 2 120x120 15 50
“180P” 10 320x180 15 140
“180P_3” 12 180x180 15 100
“180P_4” 13 240x180 15 120
“240P” 20 320x240 15 200
“240P_3” 22 240x240 15 140
“240P_4” 24 424x240 15 220
“360P” 30 640x360 15 400
“360P_3” 32 360x360 15 260
“360P_4” 33 640x360 30 600
“360P_6” 35 360x360 30 400
“360P_7” 36 480x360 15 320
“360P_8” 37 480x360 30 490
“360P_9” 38 640x360 15 800
“360P_10” 39 640x360 24 800
“360P_11” 100 640x360 24 1000
“480P” 40 640x480 15 500
“480P_3” 42 480x480 15 400
“480P_4” 43 640x480 30 750
“480P_6” 45 480x480 30 600
“480P_8” 47 848x480 15 610
“480P_9” 48 848x480 30 930
“720P” 50 1280x720 * [1] 15 1130
“720P_3” 52 1280x720 * [1] 30 1710
“720P_5” 54 960x720 * [1] 15 910
“720P_6” 55 960x720 * [1] 30 1380

Footnotes

[1](1, 2, 3, 4) Achieving 720P resolution depends on the performance and capabilities of the device and may not currently be possible on lower performance devices. If a device has inadequate performance then low frame rates may be experienced when using 720P. Agora.io is continuing to optimize video for lower-end devices in future releases – contact support@agora.io to discuss particular device needs.

Sample code:

stream.setVideoProfile('480p');