Skip to contentSkip to navigationSkip to topbar
On this page

Voice JavaScript SDK: Twilio.Call


(information)

Info

You're viewing the documentation for the 2.X version of the Voice JavaScript SDK. View the Migration Guide to learn how to migrate from 1.X to 2.X or view the 1.x-specific documentation.

A Twilio.Call object represents a call to or from Twilio. You never instantiate a Call directly, but a Call instance is passed to the event handlers for errorEvent and incomingEvent, returned when you invoke device.connect(), and returned via the device.calls accessor.

1
const device = new Device(token);
2
3
// Make an outgoing call
4
async function makeOutgoingCall() {
5
const call = await device.connect();
6
}
7
8
// or handle an incoming call
9
device.on('incoming', call => {});

Table of Contents

table-of-contents page anchor

This section contains descriptions of the methods available on a Call instance.

call.accept()

call.disconnect()

call.getLocalStream()

call.getRemoteStream()
call.ignore()

call.isMuted()

call.mute()

call.postFeedback()
call.reject()

call.sendDigits()

call.sendMessage()

call.status()

call.accept(acceptOptions)

callacceptacceptoptions page anchor

Accepts an incoming voice call, initiates a media session for the Call instance. Returns void.

The optional acceptOptions parameter is a JavaScript object that allows you to configure the WebRTC connection and the MediaStream.

The properties of the acceptOptions object are listed in the table below. Both properties are optional.

acceptOptions propertyDescription
rtcConfiguration optionalAn RTCConfiguration(link takes you to an external page) dictionary to pass to the RTCPeerConnection(link takes you to an external page) constructor. This allows you to configure the WebRTC connection between your local machine and the remote peer.
rtcConstraints optionalA MediaStreamConstraints(link takes you to an external page) dictionary to pass to getUserMedia(link takes you to an external page) when accepting a Call. This allows you to configure the behavior of tracks returned in the MediaStream(link takes you to an external page). Each browser implements a different set of MediaTrackConstraints, so consult your browser's implementation of getUserMedia for more information.

Example:

1
const acceptOptions = {
2
rtcConfiguration: {...}
3
rtcConstraints: {...}
4
};
5
6
// This could be invoked by the user clicking
7
// an "Answer Incoming Call" button
8
call.accept(acceptOptions)

The call.status() will be set to connecting while the media session for the Call instance is being set up.

The call.status() will change to open once the media session has been established.

Close the media session associated with the Call instance. Returns void.

call.getLocalStream()

callgetlocalstream page anchor

Get the local MediaStream being used by the Call instance. Returns void.

This contains the local Device instance's audio input.

call.getRemoteStream()

callgetremotestream page anchor

Get the remote MediaStream. Returns the remote MediaStream if set. Otherwise, returns undefined.

This contains the remote caller's audio, which is being received locally and output through the local user's speakers.

Ignore a pending call without alerting the dialing party. Returns void.

This method will stop incoming sound for the local Device instance and set the call.status() to closed.

This method will not send a hangup message to the dialing party.

The dialing party will continue to hear ringing until another Device instance with the same identity accepts the Call or if the Call times out.

Returns a Boolean indicating whether the input audio of the local Device instance is muted.

call.mute(shouldMute?)

callmuteshouldmute page anchor

Mutes or unmutes the local user's input audio based on the Boolean shouldMute argument you provide.

shouldMute defaults to true when no argument is passed.

1
// Passing true or no argument will mute
2
// the local device's input audio
3
call.mute(true);
4
call.mute();
5
6
7
// Unmute the input audio
8
call.mute(false);

call.postFeedback(score?, issue?)

callpostfeedbackscore-issue page anchor

Creates a Feedback resource for the Call resource associated with the Call instance. If no parameters are passed, Twilio will report that feedback was not available for this call. Returns an empty Promise.

Posting the feedback using this API will enable you to understand which factors contribute to audio quality problems.

Twilio will be able to correlate the metrics with perceived call quality and provide an accurate picture of the factors affecting your users' call experience.

For a high-level overview of your call feedback, you can use the FeedbackSummary Resource.

Parameter: feedbackScoreoptional

Data Type:

number or undefined

Description:

The end user's rating of the call using an integer (1, 2, 3, 4, or 5) or undefined if the user declined to give feedback. Suggested score interpretations are as follows:

  • 1 - Terrible call quality, call dropped, or caused great difficulty in communicating
  • 2 - Bad call quality; choppy audio, periodic one-way-audio
  • 3 - Average call quality; manageable with some noise/minor packet loss
  • 4 - Good call quality; minor issues
  • 5 - Great call quality; no issues

Parameter: feedbackIssueoptional

Data Type:

string

Description:

The primary issue that the end user experienced on the call. The possible values are as follows:

  • 'dropped-call' - Call initially connected but was dropped
  • 'audio-latency' - Participants can hear each other but with significant delay
  • 'one-way-audio' - One participant couldn't hear the other
  • 'choppy-audio' - Periodically, participants couldn't hear each other. Some words were lost
  • 'noisy-call' - There was disturbance, background noise, low clarity
  • 'echo' - There was echo during the call

Example:

1
// Pass feedbackScore only
2
call.postFeedback(5);
3
4
// Pass feedbackScore and feedbackIssue
5
call.postFeedback(2, 'dropped-call');
6
7
// Pass no arguments when user declines to provide feedback
8
call.postFeedback();
9

Reject an incoming call. Returns void.

This will cause a hangup to be issued to the dialing party.

call.sendDigits(digits)

callsenddigitsdigits page anchor

Play DTMF tones. This is useful when dialing an extension or when an automated phone menu expects DTMF tones. Returns void.

The digits parameter is a string and can contain the characters 0-9, *, #, and w. Each w will cause a 500-millisecond pause between digits sent.

The SDK only supports sending DTMF digits. It does not raise events if DTMF digits are present in the incoming audio stream.

call.sendMessage(message)

callsendmessagemessage page anchor

Note: This method is part of the Call Message Events feature.

Send a message to the server-side application.

The call.sendMessage() method takes an argument object with the following properties:

PropertyDescription
content objectThe content of the message you wish to send to the server-side application.
contentType stringThe Content-Type of the message. Currently, the value will only be "application/json"
messageType stringThe type of message sent from the server-side application. Currently, the value will only be "user-defined-message".

Send a message to the server-side application:

1
// the Call is active
2
3
const messageObject = {
4
content: { key1: 'This is a messsage from the client side'},
5
messageType: 'user-defined-message',
6
contentType: "application/json"
7
}
8
9
call.sendMessage(messageObject)

If the message was successfully sent to Twilio (which will then send the message to the subscription callback endpoint), the messageSent event will be emitted by the Call instance.

Return the status of the Call instance.

The possible status values are as follows:

StatusDescription
"closed"The media session associated with the call has been disconnected.
"connecting"The call was accepted by or initiated by the local Device instance and the media session is being set up.
"open"The media session associated with the call has been established.
"pending"The call is incoming and hasn't yet been accepted.
"reconnecting"The ICE connection was disconnected and a reconnection has been triggered.
"ringing"The callee has been notified of the call but has not yet responded.

This section describes the different events(link takes you to an external page) that can be emitted by a Call instance. Using event handlers allow you customize the behavior of your application when an event occurs, such as updating the UI when a call has been accepted or disconnected.

Emitted when an incoming Call is accepted. For outgoing calls, the'accept' event is emitted when the media session for the call has finished being set up.

The event listener will receive the Call instance.

Listen for the 'accept' event:

1
call.on('accept', call => {
2
console.log('The incoming call was accepted or the outgoing call's media session has finished setting up.');
3
});

Emitted when the HTMLAudioElement for the remote audio is created. The handler function receives the HTMLAudioElement for the remote audio as its sole argument. This event can be used to redirect media if your environment supports it. See WebRTC redirection for more details.

Emitted when the Call instance has been canceled by the remote end and the call.status() has transitioned to 'closed'.

Listen for the 'cancel' event:

1
call.on('cancel', () => {
2
console.log('The call has been canceled.');
3
});

Emitted when the media session associated with the Call instance is disconnected.

The event listener will receive the Call instance.

Listen for the 'disconnect' event:

1
call.on('disconnect', call => {
2
console.log('The call has been disconnected.');
3
});

Emitted when the Call instance receives an error.

The event listener will receive a TwilioError object.

TwilioError

twilioerror page anchor

The format of the TwilioError returned from the error event is a JavaScript object with the following properties:

PropertyDescription
causes string[]A list of possible causes for the error
code numberThe numerical code associated with this error
description stringA description of what the error means
explanation stringAn explanation of when the error may be observed
message stringAny further information discovered and passed along at runtime.
name stringThe name of this error
originalError (optional) stringThe original error received from the external system, if any
solutions string[]A list of potential solutions for the error

Listen for the 'error' event:

1
call.on('error', (error) => {
2
console.log('An error has occurred: ', error);
3
});

See a list of common errors on the Voice SDK Error Codes Page.

Note: This method is part of the Call Message Events feature.

Emitted when the Call instance receives a message sent from the server-side application.

The event listener receives a message object with the following properties:

PropertyDescription
contentThe message sent from the server-side application.
contentTypeThe Content-Type of the message. Currently, the value will only be "application/json"
messageTypeThe type of message sent from the server-side application. Currently, the value will only be "user-defined-message".
voiceEventSidA unique identifier for this message. This can be used for internal logging/tracking.

Listen for the 'messageReceived' event:

1
call.on('messageReceived', (message) => {
2
console.log('Message received:')
3
console.log(JSON.stringify(message.content));
4
});

Note: This method is part of the Call Message Events feature.

Emitted when the Call instance sends a message to the server-side application using the call.sendMessage() method.

The event listener receives a message object with the following properties:

PropertyDescription
contentThe message sent from the server-side application.
contentTypeThe Content-Type of the message. Currently, the value will only be "application/json"
messageTypeThe type of message sent from the server-side application. Currently, the value will only be "user-defined-message".
voiceEventSidA unique identifier for this message. This can be used for internal logging/tracking.

Listen for the 'messageSent' event:

1
call.on('messageSent', (message) => {
2
// voiceEventSid can be used for tracking the message
3
const voiceEventSid = message.voiceEventSid;
4
console.log('Message sent. voiceEventSid: ', voiceEventSid)
5
});

Note: If call.sendMessage() was invoked and the 'messageSent' event was not emitted, check the Device instance's error handler.

Emitted when the input audio associated with the Call instance is muted or unmuted.

The event listener will receive two arguments:

  • a Boolean indicating whether the input audio for the Call instance is currently muted
  • the Call instance

Listen for the 'mute' event:

1
call.on('mute', (isMuted, call) => {
2
// isMuted is true if the input audio is currently muted
3
// i.e. The remote participant CANNOT hear local device's input
4
5
// isMuted is false if the input audio is currently unmuted
6
// i.e. The remote participant CAN hear local device's input
7
8
isMuted ? console.log('muted') : console.log('unmuted');
9
});

Emitted when the Call instance has regained media and/or signaling connectivity.

Listen for the 'reconnected' event:

1
call.on('reconnected', () => {
2
console.log('The call has regained connectivity.')
3
});

Emitted when the Call instance has lost media and/or signaling connectivity and is reconnecting.

The event listener will receive a TwilioError object describing the error that caused the media and/or signaling connectivity loss.

You may want to use this event to update the UI so that the user is aware of the connectivity loss and that the SDK is attempting to reconnect.

Listen for the 'reconnecting' event:

1
call.on('reconnecting', (twilioError) => {
2
// update the UI to alert user that connectivity was lost
3
// and that the SDK is trying to reconnect
4
showReconnectingMessageInBrowser();
5
6
// You may also want to view the TwilioError:
7
console.log('Connectivity error: ', twilioError);
8
});

Emitted when call.reject() was invoked and the call.status() is closed.

Listen for the 'reject' event:

1
call.on('reject', () => {
2
console.log('The call was rejected.');
3
});

Emitted when the Call has entered the ringing state.

When using the Dial verb with answerOnBridge=true, the ringing state will begin when the callee has been notified of the call and will transition into open after the callee accepts the call, or closed if the call is rejected or cancelled.

The parameter hasEarlyMedia denotes whether there is early media available from the callee. If true, the Client SDK will automatically play the early media. Sometimes this is ringing, other times it may be an important message about the call. If false, there is no remote media to play, so the application may want to play its own outgoing ringtone sound.

Listen for the 'ringing' event:

1
call.on('ringing', hasEarlyMedia => {
2
showRingingIndicator();
3
if (!hasEarlyMedia) {
4
playOutgoingRinging();
5
}
6
});

Emitted when the Call instance receives a WebRTC sample object. This event is published every second.

The event listener will receive the WebRTC sample object.

Listen for the 'sample' event:

1
call.on('sample', sample => {
2
// Do something
3
});

Example of WebRTC Sample Data

1
{
2
"audioInputLevel": 11122,
3
"audioOutputLevel": 2138,
4
"bytesReceived": 8600,
5
"bytesSent": 8600,
6
"codecName": "opus",
7
"jitter": 0,
8
"mos": 4.397229249317001,
9
"packetsLost": 0,
10
"packetsLostFraction": 0,
11
"packetsReceived": 50,
12
"packetsSent": 50,
13
"rtt": 77,
14
"timestamp": 1572301567032.327,
15
"totals": {
16
"bytesReceived": 63640,
17
"bytesSent": 83936,
18
"packetsLost": 0,
19
"packetsLostFraction": 0,
20
"packetsReceived": 370,
21
"packetsSent": 488
22
}
23
}

Emitted every 50 milliseconds with the current input and output volumes on every animation frame(link takes you to an external page).

The event listener will be invoked up to 60 times per second and will scale down dynamically on slower devices to preserve performance.

The event listener will receive inputVolume and outputVolume as percentages of maximum volume represented by a floating point number between 0.0 and 1.0 (inclusive). This value represents a range of relative decibel values between -100dB and -30dB.

Listen for the 'volume' event:

1
call.on('volume', (inputVolume, outputVolume) => {
2
// Do something
3
});

You may want to use this to display volume levels in the browser. See the Voice JavaScript SDK quickstart GitHub repository(link takes you to an external page) for an example of how to implement this functionality.

Emitted when a call quality metric has crossed a threshold.

The event listener will receive two arguments:

  1. a string of the warning name (ex: 'high-rtt')
  2. an object containing data on the warning

This event is raised when the SDK detects a drop in call quality or other conditions that may indicate the user is having trouble with the call. You can implement callbacks on these events to alert the user of an issue.

To alert the user that an issue has been resolved, you can listen for the warning-cleared event, which indicates that a call quality metric has returned to normal.

For a full list of conditions that will raise a warning event, check the Voice Insights SDK Events Reference page.

The example below shows how you can listen for and handle warning events.

1
call.on('warning', function(warningName, warningData) {
2
if (warningName === 'low-mos') {
3
showQualityWarningModal('We have detected poor call quality conditions. You may experience degraded call quality.');
4
console.log(warningData);
5
/* Prints the following
6
{
7
// Stat name
8
"name": "mos",
9
10
// Array of mos values in the past 5 samples that triggered the warning
11
"values": [2, 2, 2, 2, 2],
12
13
// Array of samples collected that triggered the warning.
14
// See sample object format here https://www.twilio.com/docs/voice/sdks/javascript/twiliocall#sample-event
15
"samples": [...],
16
17
// The threshold configuration.
18
// In this example, low-mos warning will be raised if the value is below 3
19
"threshold": {
20
"name": "min",
21
"value": 3
22
}
23
}
24
*/
25
}
26
});

Emitted when a call quality metric has returned to normal.

The event listener will receive one argument, the warning name as a string (ex: 'low-mos').

You can listen for this event to update the user when a call quality issue has been resolved. See example below.

1
call.on('warning-cleared', function(warningName) {
2
if (warningName === 'low-mos') {
3
hideQualityWarningModal();
4
}
5
});

For calls that have undergone SHAKEN/STIR validation, call.callerInfo will return an object with an isVerified property.

If a caller's identity has been verified by Twilio and has achieved level A attestation, the call.callerInfo.isVerified property will be true.

1
console.log(call.callerInfo);
2
3
// PRINTS:
4
// { isVerified: true }

If a call has failed validation or if the call achieves an attestation lower than level A, the call.callerInfo.isVerified property will be false.

1
console.log(call.callerInfo);
2
3
// PRINTS:
4
// { isVerified: false }

For calls with no caller verification information, call.callerInfo will have a value of null.

1
console.log(call.callerInfo);
2
3
// PRINTS:
4
// null

Returns a Map object containing the custom parameters that were passed in the ConnectOptions.params property when invoking device.connect().

These custom parameters will be sent in the body of the HTTP request that Twilio will send to your TwiML App's Voice Configuration URL.

1
var params = {
2
To: "+15554448888",
3
aCustomParameter: "the value of your custom parameter"
4
};
5
6
const call = await device.connect({ params });
7
8
console.log(call.customParameters);
9
10
// PRINTS:
11
// {'To' => '+15554448888', 'aCustomParameter' => 'the value of your custom parameter'}
12

Returns the Call parameters received from Twilio.

For incoming calls, the call.parameters may look like this:

1
console.log(call.parameters);
2
3
// PRINTS:
4
// {
5
// From: "+15554448888",
6
// CallSid: "CAxxxx...",
7
// To: "client:YourDeviceIdentity",
8
// AccountSid: "ACxxxx..."
9
// }

For outgoing calls, the call may not yet have a CallSID. You can find the CallSID by waiting until the Twilio.Call instance has emitted the 'accept' event.

1
const call = await device.connect({ params });
2
3
console.log(call.parameters);
4
5
// PRINTS:
6
// {}
7
8
9
// For outgoing calls, the "accept" event is emitted when the Call's media session has finished setting up.
10
call.on("accept", () => {
11
console.log(call.parameters)
12
});
13
14
// PRINTS:
15
// { CallSID: "CAxxxx..." }

Returns the audio codec used for the RTCPeerConnection(link takes you to an external page) associated with the Call instance.

Possible values are "opus" and "pcmu".

1
console.log(call.codec);
2
3
// Prints:
4
// "pcmu"

The connect token is available as soon as the call is established and connected to Twilio. Use this token to reconnect to a call via the device.connect() method.

For incoming calls, the connect token is available in the call object after the device's incoming event is emitted. For outgoing calls, the connect token is available after the call's accept event is emitted.

1
console.log(call.connectToken);
2
3
// Prints:
4
// "JTdCJTIyY3VzdG9tUGFyYW1ldGVycyUyMiUzQSU3QiUyMnJlY2Vw..."

Returns the directionality of the Call instance.

Possible values are "INCOMING" and "OUTGOING".

An incoming call is one that is directed towards your Device instance.

An outgoing call is one that is made by invoking device.connect().

1
console.log(call.direction);
2
3
// Prints:
4
// "OUTGOING"

EventEmitter Methods and Properties

eventemitter-methods-and-properties page anchor

A Call instance is an EventEmitter(link takes you to an external page), so it provides a variety of event-related methods and properties. Although it will not be covered here, more information on EventEmitter functionality can be found in the full Node.js Events documentation(link takes you to an external page). Alternatively, you can click on the method/property below to be taken to the pertaining documentation.

Need some help?

Terms of service

Copyright © 2024 Twilio Inc.