WebRTC Interface Version 2 Application Developer Guide - aculab-com/aculab-webrtc GitHub Wiki

How to Write WebRTC Apps

This guide shows the basic steps how to write WebRTC applications for Aculab Cloud. Refer to the API guide for detailed documentation on the APIs used.

WebRTC Client instances can call, and be called from, Aculab Cloud services only. They cannot call PSTN or SIP phones directly, although of course Aculab Cloud services can call those devices.

A web page can handle a number of concurrent WebRTC Client instances. The maximum number of concurrent instances is browser dependent. The code shown in the Integrating WebRTC section handles only one concurrent WebRTC Client instance.

Integrating WebRTC

The WebRTC specification is currently a moving target and, along with the rest of the industry, we do our best to keep in step with it. Before deployment, please be sure to try out our WebRTC interface in the environment where you expect to use it.

  • Include the JavaScript library by adding the following line to your HTML header:

    <script src="https://webrtc.aculabcloud.net/js/2/AculabCloudCaller.js" type="text/javascript"></script>
  • In your HTML page, create a WebRTC element by adding the following:

    <audio id="player"></audio>

Registering a WebRTC Client Instance with Aculab Cloud

To register a WebRTC Client instance for use with Aculab Cloud, you will need the following information:

Information Description
Cloud ID The Cloud ID for your Aculab Cloud account, for example 1-2-0.
WebRTC Access Key Your WebRTC Access Key which can be found in the Aculab Cloud Console.
Client Id A text identifier which Aculab Cloud uses to identify a specific WebRTC Client instance.

Basics of Registering an Instance

All WebRTC calls are controlled through the AculabCloudClient class. Create a new instance of the class with:

var cloudId = "1-2-0";
var webRtcAccessKey = "3krt4sfjo...";
var clientId = "myClient-4369";
var logLevel = 2;
acc = new AculabCloudClient(cloudId, webRtcAccessKey, clientId, logLevel);

where logLevel is between 0 and 6 inclusive. 0 disables logging.

If you will be accepting incoming WebRTC calls, then set up maxConcurrent, onIncoming and onIncomingState properties. The example code in this guide assumes only 1 call at a time.

acc.maxConcurrent = number; //number of concurrent WebRTC calls to handle
acc.onIncoming = newCall;
acc.onIncomingState = incomingState;

See Accepting an Incoming WebRTC Call for information on the newCall and incomingState functions.

Enabling Incoming Calls on a WebRTC Client Instance

A WebRTC Client instance needs a token to be able to receive incoming WebRTC calls. This token is retrieved from the webrtc_generate_token Web Services API. It should be generated by server side code, so the client does not know your web services API access key. An example as follows:

fetch('/get_webrtc_token_for_client', {
    method: 'POST',
    body: clientId
  })
  .then(response => response.json())
  .then(data => acc.enableIncoming(data.token));

The onIncomingState callback is used to notify you if incoming WebRTC calls are enabled or disabled.

Calling an Aculab Cloud Service from WebRTC

WebRTC Client instances can only call Aculab Cloud inbound services. This is achieved by calling AculabCloudClient.makeOutgoing() then setting up the AculabCloudOutgoingCall callbacks to handle the call control events.

call = acc.makeOutgoing(encodeURIComponent("incoming_service_name"));
call.onDisconnect = callDisconnected;
call.onRinging = callRinging;
call.onMedia = gotMedia;
call.onConnecting = connecting;
call.onConnected = connected;

See Call Control Callbacks for information on these callbacks.

Calling a WebRTC Client Instance from Aculab Cloud

UAS and REST applications can call a WebRTC Client instance by setting the call destination to webrtc:.

The Caller ID specified is passed to the onIncoming callback.

Calling a WebRTC Client Instance from the REST API Version 2.0

An example of using the Connect action to call a WebRTC Client instance, written in Python.

my_connect = Connect()
my_connect.set_next_page("/call_finished")
my_connect.append_destination("webrtc:{0}".format(clientId))
my_connect.set_call_from('441234567890')
my_connect.set_hold_media(Play(file_to_play='holdmusic.wav'))
my_connect.set_secondary_call(SecondaryCall(first_page=WebPage(url='secondary_first'),
                                            final_page=WebPage(url='secondary_final'),
                                            error_page=WebPage(url='error_page')))

Calling a WebRTC Client Instance from the UAS API

A Python example of using the UASCallChannel object to call a WebRTC Client instance.

if channel.start_call('webrtc:{0}'.format(clientId), call_from='441234567890') is True:
    # we have started an outbound call
    pass

Accepting an Incoming WebRTC Call

onIncomingState

onIncomingState is used to inform you whether incoming WebRTC calls are enabled or disabled.

function incomingState(obj) {
    if (obj.ready) {
        // We can receive incoming calls
    } else {
        // We cannot receive incoming calls
        // Report obj.cause to the user
    }
}

onIncoming

If WebRTC Client has been configured to accept incoming calls, then the onIncoming callback is used to accept any incoming call.

The onIncoming callback should set up the AculabCloudIncomingCall callbacks, connect audio to the player, and send the ringing notification to the remote end.

// newCall has been assigned to the onIncoming callback above
function newCall(obj) {
    call = obj.call;
    callerId = obj.from;
    inbound = true;

    // Set up callbacks
    call.onDisconnect = callDisconnected;
    call.onMedia = gotMedia;
    call.onConnecting = connecting;
    call.onConnected = connected;

    // Play a ringing to notify user of the call
    // get the <audio> element
    var player = document.getElementById('player');
    if (player.canPlayType('audio/wav')) {
        player.loop = 'loop';
        player.src = 'audio/ringing.wav';
        player.type = 'audio/wav';
        player.load();
        var p = player.play();
        if (p !== undefined) {
            p.catch(error => {
                // Handle error
            });
        }
    } else {
        // Browser can't play audio/wav
    }

    // Send ringing notification to the caller
    call.ringing();
}

See Call Control Callbacks for information on these callbacks.

Call Control Callbacks

The various call control callbacks have been set up in the code snippets above. Example code showing how these callbacks are implemented is shown in this section.

onDisconnect

This callback is called when the call has been disconnected. The player element should be reset, and any resources cleaned up.

function callDisconnected(obj) {
    // Notify the user that the call has disconnected.

    // Stop anything that is playing
    stopPlayer();

    // reset state
    call = null;
    inbound = false;
    isconnected = false;
}

// Function to stop the <audio> element playing.
// This is used by the callDisconnected and gotMedia callbacks.
function stopPlayer() {
    // Get the <audio> element
    var player = document.getElementById('player');
 
    // Reset the player state
    player.pause();
    player.loop = '';
    player.src = '';
    player.srcObject = null;
    player.type = '';
    player.load();
    playing_ringing = false;
    gotremotestream = false;
}

onRinging

If you have not got an audio stream from the remote end, then you can generate a ringtone locally.

function callRinging(obj) {
    // get the <audio> element
    var player = document.getElementById('player');
    if (!playing_ringing) {
        if (player.canPlayType('audio/wav')) {
            // Play a ringback tone if we have not got an audio stream
            // from the remote end
            // gotremotestream is initialised in gotMedia()
            if (!gotremotestream) {
                player.loop = 'loop';
                player.src = 'audio/ringback.wav';
                player.type = 'audio/wav';
                player.load();
                var p = player.play();
                if (p !== undefined) {
                    p.catch(error => {
                        // Handle error
                    });
                }
            }
        } else {
            // Browser can't play audio/wav
        }
        playing_ringing = true;
    }
}

onMedia

The onMedia callback is used to give you the remote audio stream which you can connect to your element.

function gotMedia(obj) {
    // Stop anything that is playing
    stopPlayer();

    var player = document.getElementById('player');
    gotremotestream = true;
    player.srcObject = obj.stream;
    player.load();
    var p = player.play();
    if (p !== undefined) {
        p.catch(error => {
            // Handle error
        });
    }
}

onConnecting

onConnecting is called when the browser is preparing the sockets needed to transport the call media. There is nothing that specifically needs doing in this callback, but it can be used to notify the user about call progress.

function connecting(obj) {
    // Update a web page element to notify the user that the
    // call is connecting
}

onConnected

When the call has been answered the onConnected callback will be called. You can use this callback to notify the user about call progress.

function connected(obj) {
    // Update a web page element to notify the user that the
    // call is connected
    isconnected = true;
}

Disconnecting a Call

Disconnecting a connected call is as simple as calling disconnect() on the call object. Inbound calls that have not connected should be rejected with a valid SIP cause, for example 486 busy here, instead.

function stopCall() {
    if (call) {
        // If inbound call has not been accepted, then reject the call
        if (inbound && !isconnected) {
            call.reject(486);
        } else {
            call.disconnect();
        }
    }
}

Troubleshooting

A number of common issues can cause problems with audio in a WebRTC call.

HTML5 autoplay blockers will prevent the element from automatically playing the audio from the remote end. Ensure that any blockers are disabled for your WebRTC page.

If the same username is registered from more than one browser instance then the most recently registered instance will receive incoming WebRTC calls. As WebRTC Client instances are automatically re-registered at various intervals, the most recently registered instance may change without warning. Therefore, in general it's best to register a given username with only one browser instance at a time.

⚠️ **GitHub.com Fallback** ⚠️