Menu

Expand
Rate this page:

Voice JavaScript SDK: Twilio.Call

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 errorEvent and incomingEvent, returned when you invoke device.connect(), and returned via the device.calls accessor.

const device = new Device(token);

// Create a new outgoing Connection
// call is a Twilio.Call instance
let call = device.connect();

// or handle an incoming Call
device.on('incoming', (call) => {
  // call is a Twilio.Call instance
  ));

Table of Contents

Methods

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

call.accept(acceptOptions)

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 property Description

rtcConfiguration

optional

An RTCConfiguration dictionary to pass to the RTCPeerConnection constructor.

This allows you to configure the WebRTC connection between your local machine and the remote peer.

rtcConstraints

optional

A MediaStreamConstraints dictonary to pass to getUserMedia when accepting a Call.

This allows you to configure the behavior of tracks returned in the MediaStream.

Each browser implements a different set of MediaTrackConstraints, so consult your browser's implementation of getUserMedia for more information.

Example:

const acceptOptions = {
  rtcConfiguration: {...}
  rtcConstraints: {...}
};

// This could be invoked by the user clicking 
// an "Answer Incoming Call" button
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.

call.disconnect()

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

call.getLocalStream()

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

This contains the local Device instance's audio input.

call.getRemoteStream()

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.

call.ignore()

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.

call.isMuted()

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

call.mute(shouldMute?)

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.

// Passing true or no argument will mute 
// the local device's input audio
call.mute(true);
call.mute();


// Unmute the input audio
call.mute(false);

call.postFeedback(score?, issue?)

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 Data Type Description

feedbackScore

optional

number or undefined

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

feedbackIssue

optional

string

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:

// Pass feedbackScore only
call.postFeedback(5); 

// Pass feedbackScore and feedbackIssue
call.postFeedback(2, 'dropped-call');

// Pass no arguments when user declines to provide feedback 
call.postFeedback(); 

call.reject()

Reject an incoming call. Returns void.

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

call.sendDigits(digits)

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.status()

Return the status of the Call instance.

The possible status values are as follows:

Status Description
"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.

Events

This section describes the different events 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.

accept Event

Emitted when the Call is accepted

The event listener will receive the Call instance.

Listen for the 'accept' event:

call.on('accept', call => {
  console.log('The incoming call was accepted.');
});

cancel Event

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

A Call instance can be canceled in two ways:

  1. Invoking call.ignore() on an incoming call
  2. Invoking call.disconnect() on an outgoing call before the recipient has answered

Listen for the 'cancel' event:

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

disconnect Event

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:

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

error Event

Emitted when the Call instance receives an error.

The event listener will receive a TwilioError object.

TwilioError

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

Property Description

causes

string[]

A list of possible causes for the error

code

number

The numerical code associated with this error

description

string

A description of what the error means

explanation

string

An explanation of when the error may be observed

message

string

Any further information discovered and passed along at runtime.

name

string

The name of this error

originalError (optional)

string

The original error received from the external system, if any

solutions

string[]

A list of potential solutions for the error

Listen for the 'error' event:

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

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

mute Event

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:

call.on('mute', (isMuted, call) => {
 // isMuted is true if the input audio is currently muted 
 // i.e. The remote participant CANNOT hear local device's input

 // isMuted is false if the input audio is currently unmuted
 // i.e. The remote participant CAN hear local device's input

 isMuted ? console.log('muted') : console.log('unmuted');
});

reject Event

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

Listen for the 'reject' event:

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

sample Event

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:

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

Example of WebRTC Sample Data

{
  "audioInputLevel": 11122,
  "audioOutputLevel": 2138,
  "bytesReceived": 8600,
  "bytesSent": 8600,
  "codecName": "opus",
  "jitter": 0,
  "mos": 4.397229249317001,
  "packetsLost": 0,
  "packetsLostFraction": 0,
  "packetsReceived": 50,
  "packetsSent": 50,
  "rtt": 77,
  "timestamp": 1572301567032.327,
  "totals": {
    "bytesReceived": 63640,
    "bytesSent": 83936,
    "packetsLost": 0,
    "packetsLostFraction": 0,
    "packetsReceived": 370,
    "packetsSent": 488
  }
}

volume Event

Emitted every 50 milliseconds with the current input and output volumes on every animation frame.

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:

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

You may want to use this to display volume levels in the browser. See the Voice JavaScript SDK quickstart GitHub repository for an example of how to implement this functionality.

warning Event

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.

call.on('warning', function(warningName, warningData) {
  if (warningName === 'low-mos') {
    showQualityWarningModal('We have detected poor call quality conditions. You may experience degraded call quality.');
    console.log(warningData);
    /* Prints the following
      {
        // Stat name
        "name": "mos",

        // Array of mos values in the past 5 samples that triggered the warning
        "values": [2, 2, 2, 2, 2],

        // Array of samples collected that triggered the warning.
        // See sample object format here https://www.twilio.com/docs/voice/client/javascript/connection#sample
        "samples": [...],

        // The threshold configuration.
        // In this example, low-mos warning will be raised if the value is below 3
        "threshold": {
          "name": "min",
          "value": 3
        }
      }
     */
  }
});

warning-cleared Event

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.

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

Accessors

call.codec

Returns the audio codec used for the RTCPeerConnection associated with the Call instance.

Possible values are "opus" and "pcmu".

console.log(call.codec);

// Prints: 
// "pcmu"

call.direction

Returns the directonality 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().

console.log(call.direction);

// Prints: 
// "OUTGOING"

EventEmitter Methods and Properties

A Call instance is an EventEmitter, 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. Alternatively, you can click on the method/property below to be taken to the pertaining documentation.

Rate this page:

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd by visiting Twilio's Community Forums or browsing the Twilio tag on Stack Overflow.

        
        
        

        Thank you for your feedback!

        We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

        Sending your feedback...
        🎉 Thank you for your feedback!
        Something went wrong. Please try again.

        Thanks for your feedback!

        Refer us and get $10 in 3 simple steps!

        Step 1

        Get link

        Get a free personal referral link here

        Step 2

        Give $10

        Your user signs up and upgrade using link

        Step 3

        Get $10

        1,250 free SMSes
        OR 1,000 free voice mins
        OR 12,000 chats
        OR more