The twilio.js Library: Twilio.Device (1.4)

The Twilio.Device object is available when twilio.js is included in your page. It represents a soft device, the client that provides connections into Twilio.

Method Reference

Twilio.Device

The following is a list of methods available on Twilio.Device:

.setup( token, [params] )

Initialize Twilio.Device with a capability token (see Twilio Client Capability Tokens). The token you provide will activate the device, give it an identity, grant it privileges to make and receive inbound and/or outbound calls, and associate it with a specific Twilio application. You should call this before anything else. If your token allows inbound client connections, the device will start listening for new connections when you call .setup().

.setup()'s params argument takes a JavaScript object containing configuration settings. Available settings are listed below:

Property Default Description
debug false Can be true or false. Set this property to true to enable debug logging in your browser console.
closeProtection false Can be boolean or string. Setting this property to true will enable a dialog prompt with the text "A call is currently in progress. Leaving or reloading this page will end the call." when closing a page which has an active connection. Setting the property to a string will change the text of the message prompt. NOTE: Where custom text is not supported on the browser, Twilio will display the browser's default dialog.
warnings true Can be true or false. Set this property to false to disable logging to your browser console when calling deprecated methods.
audioConstraints true Can be true or MediaTrackConstraints. Set this property to select a specific microphone, or turn off features like auto-gain control, for the entire Twilio.Device. Each web browser implements a different set of MediaTrackConstraints, so consult your browser's implementation of getUserMedia for further details. This property can also be overridden for each Twilio.Connection. See also our knowledge base article on audioConstraints. Note: If an input device is selected using Device.audio.setInputDevice, this parameter will be ignored and the set input device will be used instead.
region gll Specifies which Twilio Data Center to use when registering, initiating calls, and receiving calls. See this page for the list of available regions, and their IP address ranges
dscp true Specifies whether Twilio Client will ask WebRTC to set the Differentiated Services field in the packet headers for all WebRTC traffic. Note: At this time, DSCP is only supported in Google Chrome.
sounds null An object mapping sound names (property) to custom URLs (string value). Note that incoming ringtone will loop for at least 2 seconds and as long as the incoming call is pending. All other sounds will play once; DTMF tones will be cut short if they exceed 1 second, while outgoing and disconnect sounds will be cut short if they exceed 3 seconds.
enableRingingState false When set to true, the new ringing state and Connection#ringing event will be enabled for calls this Device makes. These features are intended to be used alongside the answerOnBridge Dial property (eg: <Dial answerOnBridge=true></Dial>) to provide better SDK feedback on the call status.

For example:

Twilio.Device.setup(token); // use the default parameters

Or using params:

Twilio.Device.setup(token, { debug: true, region: "ie1" }); // enable debug logging and establish connections through Twilio's data center in Ireland

Or using custom sounds:

Twilio.Device.setup(token, {
  sounds: {
    incoming: 'http://mysite.com/incoming.mp3',
    outgoing: 'http://mysite.com/outgoing.mp3',
    dtmf8: 'http://mysite.com/funny_noise.mp3'
  }
}

.ready( handler(device) )

Register a handler function to be called when the ready event is fired. This is initially triggered when all operations in .setup() have completed and the device is ready and online. It may be triggered again if the device goes offline and comes back online (i.e. the connection drops and returns).

The handler function receives the Twilio.Device object as its sole argument.

Twilio.Device.ready(function(device) {
  // The device is now ready
  console.log("Twilio.Device is now ready for connections");
});

.offline( handler(device) )

Register a handler function to be called when the offline event is fired. This is triggered when the connection to Twilio drops or the device's capability token is invalid/expired. In either of these scenarios, the device cannot receive incoming connections or make outgoing connections. If the token expires during an active connection the offline event handler will be called, but the connection will not be terminated. In this situation you will have to call Twilio.Device.setup() with a valid token before attempting or receiving the next connection.

The handler function receives the Twilio.Device object as its sole argument.

We strongly recommend you implement an .offline() event handler before putting your application into production so that your application handles these scenarios gracefully.

.incoming( handler(connection) )

Register a handler function to be called when an incoming event is fired. This is triggered whenever an incoming connection from an outbound REST call or a TwiML <Dial> to this device is made.

Remember, to enable incoming connections you must give your device a name using the Capability Token you provided in .setup(token). See the Client Quickstart on receiving incoming connections for more information.

The handler function receives a Twilio.Connection object as an argument. This connection will be in state pending until you call .accept() on it.

Twilio.Device.incoming(function(connection) {
  connection.accept();
  // do awesome ui stuff here
  // $('#call-status').text("you're on a call!");
});

.cancel( handler(connection) )

Register a handler function to be called when the device receives a canceled event. This is triggered when an incoming connection is canceled by the caller before it is accepted by the Twilio Client device.

The handler function receives a Twilio.Connection object as an argument. Since this Connection object represents an inactive connection, you'll probably just want to use the event to update your application's UI, then throw away the Connection and wait for the next call.

.connect( handler(connection) )

Register a handler function to be called when the device receives a connect event. This is triggered when a connection is opened, whether initiated using .connect() or via an accepted incoming connection.

The handler function receives a Twilio.Connection object as an argument.

.connect( [params [, audioConstraints]] )

Attempts a new connection to the Twilio application that you associated with this Device's capability token when you called .setup() (see Twilio Client Capability Tokens for more information).

The optional params argument is a JavaScript object which will be passed to your application as POST/GET parameters.

Your application should not assume that these parameters are safe since any user can call this function with whatever parameters she wants.

For example, the following code will pass the params agent=Smith and location=Matrix to the Twilio application associated with this Device's capability token.

var connection = Twilio.Device.connect({
  agent: "Smith",
  location: "Matrix"
});

You can also specify an audioConstraints object to change the behavior of the local media stream during this call. You can use this to select a specific microphone, or turn off features like auto-gain control. Each web browser implements a different set of MediaTrackConstraints which may be used as audioConstraints, so consult your browser's implementation of getUserMedia for further details.

var audioConstraints = {
  optional: [{ sourceId: 'XXX' }]
};

var connection = Twilio.Device.connect(null, audioConstraints);

The .connect() method returns a Twilio.Connection object. You can end the connection by calling its .disconnect() method.

Example VoiceUrl TwiML

When you call .connect(), the client will attempt a new connection to the Twilio Application you use in your Twilio.Device's capability token. This application can do whatever you like: Make a phone call to a phone number or Twilio Client address, start a conference call, interact with an IVR, etc.

For example, if your application's VoiceUrl returns the following TwiML:

<Response>
  <Dial callerId="+1888XXXXXXX">
    415-867-5309
  </Dial>
</Response>

then your device will make a call to 415-867-5309 every time you call .connect().

All of TwiML is available to your client applications.

You can use the params passed to the application in .connect() to dynamically generate the right TwiML for your app. For example, you could do the following in your JavaScript code:

var number = '5558675309';
var connection = Twilio.Device.connect({
  phone: number
});

And in the web application that generates your TwiML, retrieve the phone parameter from the HTTP request and insert into your TwiML as follows:

<Response>
  <Dial callerId="+1888XXXXXXX">
    5558675309
  </Dial>
</Response>

.activeConnection()

Returns the active connection object. Connection objects can be used to perform operations on the connection like mute, unmute, sending DTMF digits, etc.

.disconnectAll()

Terminates the active connection. This will trigger the disconnect event handler. It will not prevent new incoming connections.

.disconnect( handler(connection) )

Register a handler function to be called any time a connection is closed. The handler function receives the Twilio.Connection object that was just closed as an argument.

.error( handler(error) )

Register a handler function to be called when any device error occurs. These may be errors in your request, your capability token, connection errors, or other application errors. See the Twilio Client error code reference for more information. Using the error handler is a great way to debug your application and help catch mistakes in your code.

The handler function receives an error object as an argument. The error object may include the following properties:

Property Description
message A string describing the error.
code A numeric error code described in the Twilio Client error code reference.
connection A reference to the Twilio.Connection object that was active when the error occurred.
Twilio.Device.error(function(error) {
  console.log(error.message);
});

.status()

Return the status of the device. The status will be one of the following strings:

Status name Description
ready The device is currently connected to Twilio and has a valid capability token.
offline The device is either not connected to Twilio or has an expired/invalid capability token.
busy The device is connected to Twilio, has an active connection, and cannot receive incoming connections or attempt outgoing connections.

.destroy()

Destroys the device. Terminates active and pending connections. This will trigger the offline event handler. Device will not be able to make or receive new connections until you call Twilio.Device.setup() again.

Twilio.Device.audio

The Device.audio object lets you control the way Twilio Client interacts with speaker and microphone resources. Device.audio is an EventEmitter, and as such its events can be subscribed to via Device.audio.on(eventName, handler).

Browser Support

NOTE: Many of audio features are browser-dependent.

Currently Chrome 49+ is the only browser that fully supports Twilio.Device.audio.

Audio output selection requires support for setSinkId. At the time of writing, this method is only supported in Chrome 49 and above, and Microsoft Edge. As Firefox adds support for these APIs, twilio.js will be updated to provide support. Although Edge supports setSinkId, it is not yet fully supported in this API.

Audio input selection requires support for AudioContext. This feature is supported in latest modern browsers (Chrome, Firefox, Edge), however twilio.js has not completed implementation in Firefox and Edge. Support is coming soon.

If these features are used in a browser that does not support them, the get method will return an empty Set, whereas the set and test methods will return a rejected Promise.

Methods

.audio.setInputDevice(id)

Set the current input device by deviceId. Once this is set, the input device will be used in the current call, if any, and used by default for any subsequent calls. In addition, whenever an inputDevice is set, the Device.audio#inputVolume event will fire on every animation frame. Returns a Promise that resolves if the input device was set successfully.

Note: This is not supported in Firefox (as recent as 51) due to its lack of support for multiple input devices.

Example
Twilio.Device.audio.setInputDevice('default').then(function() {
  console.info('Success!');
});

.audio.unsetInputDevice(id)

Unset the active input device. This will stop the Device.audio#inputVolume polling, and stop the input stream.

Example
Twilio.Device.audio.unsetInputDevice().then(function() {
  console.info('Success!');
});

Properties

.audio.availableOutputDevices

A Map containing the MediaDeviceInfo object of all available output devices (hardware devices capable of outputting audio), indexed by deviceId.

Note: Due to browser-imposed security restrictions, MediaDeviceInfos available in availableOutputDevices will contain auto-generated labels (e.g. “Unknown Audio Output Device 1”) until the user grants the application access to these resources in response to a call to the browser's getUserMedia() API. Twilio Client will automatically call getUserMedia() when you accept an incoming call or initiate an outgoing call, or you can call it yourself in advance of placing a call.

Also Note: Firefox (as recent as 51) does not list any audiooutput devices, and Edge (as recent as 38) does not label its audiooutput devices even after user permission is granted.

After the user accepts the getUserMedia() prompt, the AudioHelper#deviceChange event will be fired to indicate that the application UI should be updated.

Example
Twilio.Device.audio.availableOutputDevices.forEach(function(device, id) {
  console.info('Available device:', id, '(labeled', device.label, ')');
});

.audio.availableInputDevices

A Map containing the MediaDeviceInfo object of all available input devices (hardware devices capable of providing an input audio stream), indexed by deviceId.

Note: Due to browser-imposed security restrictions, MediaDeviceInfos available in availableOutputDevices will contain auto-generated labels (e.g. “Unknown Audio Output Device 1”) until the user grants the application access to these resources in response to a call to the browser's getUserMedia() API. Twilio Client will automatically call getUserMedia() when you accept an incoming call or initiate an outgoing call, or you can call it yourself in advance of placing a call.

After the user accepts the getUserMedia() prompt, the AudioHelper#deviceChange event will be fired to indicate that the application UI should be updated.

.audio.inputDevice

A MediaDeviceInfo representing the input device selected by .audio.setInputDevice(), or null.

Twilio.Device.audio.speakerDevices

speakerDevices is an AudioOutputCollection that controls which output devices are used to play standard speaker sounds: the ringtone you hear when initiating a call, the disconnect sound, DTMF tones the user might press and the audio received from the remote participant. Changing this set of devices will switch the device(s) used for these sounds. If you change these during an active call, the remote participant’s audio will immediately be played through the new set of outputs.

Note: This is not supported in Firefox (as recent as 51) or Edge (as recent as 38) due to their lack of support for HTMLAudioElement.setSinkId().

Quick API Reference
// Returns a Set<MediaDeviceInfo> of the current speakerDevices
Twilio.Device.audio.speakerDevices.get(); 
// Set the active device to the default
Twilio.Device.audio.speakerDevices.set('default');
// Set the active devices to the default and ABC123
Twilio.Device.audio.speakerDevices.set(['default', 'ABC123']); 

Twilio.Device.audio.ringtoneDevices

ringtoneDevices is an AudioOutputCollection that controls which output devices are used to play the ringing sound when receiving an incoming call. Changing this set of devices will switch the devices used for the incoming call sound.

Note: This is not supported in Firefox (as recent as 51) or Edge (as recent as 38) due to their lack of support for HTMLAudioElement.setSinkId().

Quick API Reference
Twilio.Device.audio.ringtoneDevices.get(); // Returns a Set<MediaDeviceInfo>
Twilio.Device.audio.ringtoneDevices.set('default'); // Set active device
Twilio.Device.audio.ringtoneDevices.set(['default', 'ABC123']); // Set active devices
Twilio.Device.audio.ringtoneDevices.test(); // Test with 'outgoing' sound
Twilio.Device.audio.ringtoneDevices.test('cowbell.mp3'); // Test with custom sound

Twilio.Device.audio.speakerDevices.test() and Twilio.Device.audio.ringtoneDevices.test()

Use the test() method on the speakderDevices or ringtoneDevices collections to play a test sound. This is a great way to let your user evaluate whether the device is working as expected by giving them audible feedback on the device configuration.

// Test that the devices have been set properly by playing 'outgoing' sound...
Twilio.Device.audio.speakerDevices.test(); 
// ... or test playback using a custom sound
Twilio.Device.audio.speakerDevices.test('cowbell.mp3'); 

event: Twilio.Device.audio#deviceChange

.audio.on('deviceChange', handler(lostActiveDevices))

Register a handler that will be fired whenever a new audio device is found, an existing audio device is lost or the label of an existing device is changed. This typically happens when the user plugs in or unplugs an audio device, like a headset or a microphone. This will also trigger after the customer has given access to user media via getUserMedia for the first time, as the labels will become populated. If you want to allow users to choose a specific audio device in your application’s UI, attach a listener to this event.

Note that this does not detect a customer plugging in headphones or other speakers through the headphone jack, as the headphone jack only redirects audio from the internal audio device.

The parameter, lostActiveDevices, is an array of MediaDeviceInfo objects that represents all devices that were currently active in either .speakerDevices or .ringtoneDevices at the time they were lost, if any. A non-empty array is an indicator that the user’s experience was likely affected by this event.

event: Twilio.Device.audio#inputVolume

.audio.on('inputVolume', handler(volume))

Register a handler that will be fired every animation frame with the current volume of the selected input device, if one is set. The handler will be invoked up to 60 times per second, and will scale down dynamically on slower devices to preserve performance. The handler receives volume as a percentage 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.

Note: This will never in Firefox (as recent as 51) as there is no supported way to set the input device.

Twilio.AudioOutputCollection

Both speakerDevices and ringtoneDevices are instances of AudioOutputCollection . An AudioOutputCollection represents active audio devices, and can be updated to redirect speaker and ringtone sounds to different devices in realtime.

audioOutputCollection.get()

Get a Set containing MediaDeviceInfo objects representing the active devices in the collection.

audioOutputCollection.set( deviceId | deviceIds )

Replace the active devices in the collection by passing one or more device IDs. Returns a Promise, which is fulfilled if the device(s) were set successfully and rejected if:

  • Output selection is not supported by the browser or
  • A specified deviceId wasn’t found or
  • No deviceIds were specified

audioOutputCollection.test( soundUrl )

Test the active devices by playing a sound through them. Optionally, a URL can be passed to play a custom test sound. Returns a Promise, which is fulfilled if the devices were set successfully and rejected if:

  • Output selection is not supported by the browser or
  • There are no active devices or
  • Client detects one or more devices failed to play
Example Usage
var speakerDeviceSelect = document.getElementById('speaker-devices');

// When a device is found or lost, update a multi-select element with the
// new set of available devices.
Twilio.Device.audio.on('deviceChange', function updateAvailableDevices() {
  speakerDeviceSelect.innerHtml = '';

  Twilio.Device.audio.availableOutputDevices.forEach(function(device, id) {
    var deviceOption = document.createElement('option');
    deviceOption.label = device.label;
    deviceOption.setAttribute('data-id', id);

    // If the device is present in Device.audio.speakerDevices, then it is
    // currently active, and should be selected in the multi-select element.
    var speakerDevices = Twilio.Device.audio.speakerDevices.get();
    if (speakerDevices.has(id)) {
      deviceOption.setAttribute('selected', 'selected');
    }

    speakerDeviceSelect.appendChild(deviceOption);
  });
});

// When a device is selected or unselected, update Device.audio.speakerDevices
// with the devices the user selected to immediately change where the audio
// is playing from.
speakerDeviceSelect.addEventListener('change', function() {
  var selectedDeviceIds = [].slice.call(speakerDevices.childNodes)
    .filter(function(node) { return node.selected; })
    .map(function(node) { return node.getAttribute('data-id'); });

  Twilio.Device.audio.speakerDevices.set(selectedDeviceIds);
});

Sound Flags

These getters/setters were moved over from the deprecated Device.sounds API. If a sound is disabled, it will not be played through any output device.

.audio.incoming( [bool] ) 

Enable or disable the incoming event sound.

.audio.incoming() 

Returns a boolean indicating whether the incoming sound is enabled or disabled.

.audio.outgoing( [bool] ) 

Enable or disable the outgoing event sound.

.audio.outgoing() 

Returns a boolean indicating whether the outgoing sound is enabled or disabled.

.audio.disconnect( [bool] ) 

Enable or disable the disconnect event sound.

.audio.disconnect() 

Returns a boolean indicating whether the disconnect sound is enabled or disabled.

Deprecated methods

twilio.js 1.3 and below exposed a sounds object on the Device. In twilio.js 1.4 and above, sounds and all of the methods defined on sounds have been moved to audio. sounds and the old versions of these methods remain available in twilio.js 1.4, but calling the methods on sounds will generate a deprecation warning. We strongly encourage you to begin using audio.

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 browsing the Twilio tag on Stack Overflow.