Twilio Voice JS SDK: Twilio.Device

The Twilio Client JavaScript SDK has been renamed to Twilio Voice JavaScript SDK.

You’re viewing the 1.X version of the Voice JavaScript SDK (formerly called Twilio Client). Click here for information on how to migrate to the 2.X version.

Twilio.Device オブジェクトはページに twilio.js が組み込まれている場合に有効になります。これは、ソフトデバイス、つまり Twilio に接続を提供するクライアントです。



Twilio.Device で利用可能なメソッドは、次の通りです。

constructor([token], [params])

As of 1.5.0, the Twilio.Device class can be constructed directly rather than used as a singleton via the Twilio.Device global. Using this method, multiple Device instances can operate on the same page simultaneously. If a token is passed, Device.setup() will be run on construction with the passed token and options. Otherwise, the new Device will wait for Device.setup(token, options) to be called before initiating a signaling connection.

const device = new Twilio.Device();
device.setup(token, options);

// or (deprecated singleton behavior)...

Twilio.Device.setup(token, options);

.setup( token, [params] )

Initialize Twilio.Device with an Access Token (see Twilio Access 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().

The maximum number of characters for the identity provided in token is 121. The identity may only contain alpha-numeric and underscore characters. Other characters, including spaces, or exceeding the maximum number of characters, will result in not being able to place or receive calls.

Best Practice Note

Browsers are cracking down on unwarranted background audio. As a result, browsers are progressively moving toward requiring a user gesture before allowing audio to play on a page. Twilio recommends calling Device.setup() in response to a user gesture, such as a click. One popular and intuitive way to implement this is to add a "ready" button that will initiate the Device and show the dialer once clicked.

.setup()params引数はJavascript オブジェクトに含まれる設定を利用します。有効な設定は下記のとおりです。

プロパティ 初期値 概要
allowIncomingWhileBusy false When set to true, Device's default behavior of silently ignoring the incoming call is removed, and the incoming call will instead cause Device to emit an "incoming" event. If accepted, the prior active call will be immediately disconnected, and the incoming call will be accepted, replacing the prior active call.
appName null A name for the application that is instantiating the Device. This is used to improve logging in Insights by associating Insights data with a specific application, particularly in the case where one account may be connected to by multiple applications.
appVersion null A version for the application that is instantiating the Device. This is used to improve logging in Insights by associating Insights data with a specific version of the given application. This can help track down when application-level bugs were introduced.
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.
backoffMaxMs 20000 The maximum amount of time, in milliseconds, to wait between websocket reconnects. The SDK uses an exponential backoff, so initially reconnection will be attempted much faster (100ms). The minimum acceptable value here is 3000.
codecPreferences ['pcmu', 'opus'] An ordered list of preferred codecs. Currently, 'pcmu' and 'opus' are supported. PCMU will remain default until the next breaking release, however we recommend testing and using Opus as it can provide better quality for lower bandwidth, particularly noticeable in poor network conditions.
closeProtection false boolean もしくは string。このプロパティを true に設定すると、接続がアクティブであるページを閉じたときにテキスト"A call is currently in progress. Leaving or reloading this page will end the call." を表示するダイアログプロンプトが有効になります。string に設定するとメッセージプロンプトを変更できます。注:カスタムテキストをサポートしてないブラウザの場合、Twilio はブラウザのデフォルトメッセージを表示します。
debug false Can be true or false. Set this property to true to enable debug logging in your browser console. This can be overridden using loglevel APIs. Please see SDK Logger section for details.
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, and does not work on Windows.
edge roaming The Edge location to connect to. In case edge is of type array, it should contain the list of edge strings sorted by priority order where the first element has the highest priority and the last element has the lowest priority. The array will be used to provide auto fallback functionality. The edge that the SDK connected to can be read from Twilio.Device using the read-only property Twilio.Device.edge.

Please see documentation on edges for more details.

enableIceRestart false When set to true, allows for detecting when media connection fails which will trigger automatic media reconnection, and for detecting when media connection is restored, as well as the Connection#reconnecting and Connection#reconnected` events.
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.
fakeLocalDTMF false If true, replaces default DTMF tones with mock DTMF tones. This prevents double-tones in some cases. This will become default in the next breaking release.
forceAggressiveIceNomination false An experimental feature for Chrome browser to enable Aggressive ICE Candidate Nomination. This feature can be enabled by setting it to true. If your deployment is on devices with one network interface and your RTT to Twilio's Servers is typically greater than 96 milliseconds, this feature may help reduce call connect time. As this is an experimental feature, we don't recommend enabling this until after testing it thoroughly in your deployment.
iceServers null An array of custom ICE servers to use to connect media. If you have custom Twilio TURN servers from Twilio NTS, you can specify them here.
maxAverageBitrate null Max average bitrate to better control how much bandwidth your VoIP application should use. See RFC-7587 section 7.1. Only applicable when using Opus codec. By default, the Opus codec is set up with a transmission rate of around 32 kbps (40-50kbps on the wire). Max Average Bitrate can be set to as low as 6,000bps and as high as 51,000 bps. Values outside this range are ignored and the default Opus operation mode is used. Lowering the max average bitrate impacts audio quality. We don’t recommend setting max average bitrate to a value below 8,000 bps. On the other hand, setting values over 32,000 bps will have negligible audio quality improvements.
region gll The region parameter is now deprecated. Please use Twilio.Device.Options.edge instead.

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
rtcConfiguration null Pass a custom RTCConfiguration object to override what Twilio uses to create RTCPeerConnections.
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. See the list of all available sound properties and their default values below.
warnings true Can be true or false. Set this property to false to disable logging warnings to your browser console. This can be overridden using loglevel APIs. Please see SDK Logger section for details.


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


// enable debug logging and use default values for all other parameters 
Twilio.Device.setup(token, { debug: true }); 

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'

Or specify an Edge location to connect to:

// edge as a string
Twilio.Device.setup(token, { edge: 'ashburn' });

// edge with auto fallback functionality
Twilio.Device.setup(token, { edge: ['ashburn', 'sydney' ] });

// edge with auto fallback functionality for private interconnect
Twilio.Device.setup(token, { edge: ['ashburn', 'san-jose-ix' ] });

Available sound properties:

Property name Default filename Default value(s)
incoming incoming shouldLoop: true
Outgoing outgoing maxDuration: 3e3
disconnect disconnect maxDuration: 3e3
dtmf1 dtmf-1 maxDuration: 1e3
dtmf2 dtmf-2 maxDuration: 1e3
dtmf3 dtmf-3 maxDuration: 1e3
dtmf4 dtmf-4 maxDuration: 1e3
dtmf5 dtmf-5 maxDuration: 1e3
dtmf6 dtmf-6 maxDuration: 1e3
dtmf7 dtmf-7 maxDuration: 1e3
dtmf8 dtmf-8 maxDuration: 1e3
dtmf9 dtmf-9 maxDuration: 1e3
dtmf0 dtmf-0 maxDuration: 1e3
dtmfs dtmf-star maxDuration: 1e3
dtmfh dtmf-hash maxDuration: 1e3

.connect( [params [, audioConstraints]] )

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

The optional params argument is a JavaScript object which will be passed to your application as POST/GET parameters. Note, the total length of all params passed in must not exceed 800 bytes. See How to Share Information Between Your Applications for more information.

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

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

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


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

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


VoiceUrl の TwiML の例

When you call .connect(), the client will attempt a new connection to the Twilio Application you use in your Twilio.Device's access 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.


  <Dial callerId="+1888XXXXXXX">




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


  <Dial callerId="+1888XXXXXXX">


コネクションオブジェクトは接続時に、mute, unmute, DTMFの数字の送信等に使われます。


Destroys the device. Terminates active and pending connections, and cleans up all event listeners attached to the Device, after triggering the offline event handler. Device will not be able to make or receive new connections until you call Device.setup() again.





ステータス名 概要
ready The device is currently connected to Twilio and has a valid Access Token.
offline The device is either not connected to Twilio or has an expired/invalid Access Token.
busy デバイスはTwilioに接続されており、アクティブなコネクションを持っています。


.runPreflight(token, options)

Returns a PreflightTest object representing a test call to Twilio which provides information to help troubleshoot call related issues. For example:

import { Device, PreflightTest } from 'twilio-client';

const preflightTest = Device.runPreflight(token, options);

preflightTest.on(PreflightTest.Events.Completed, (report) => {

preflightTest.on(PreflightTest.Events.Failed, (error) => {

The token parameter is passed directly to the Device's constructor and will be used to connect to a TwiML app that you associated with your token. In order to get better results, the TwiML app should be able to record audio from a microphone and play it back to the browser. Please see Preflight Test TwiML Apps for details.

The options parameter is a JavaScript object containing configuration settings. Available settings are listed below:

プロパティ 初期値 概要
codecPreferences ['pcmu', 'opus'] An ordered list of preferred codecs.
debug false Set this property to true to enable debug logging in your browser console.
edge roaming Specifies which Twilio edge to use when initiating the test call. Please see documentation on edges.
fakeMicInput false If set to true, the test call will ignore microphone input and will use a default audio file. If set to false, the test call will capture the audio from the microphone.
signalingTimeoutMs 10000 Amount of time to wait for setting up signaling connection.
iceServers null An array of custom ICE servers to use to connect media. If you provide both STUN and TURN server configurations, the test will detect whether a TURN server is required to establish a connection.


Note that any event handlers set here will be removed when calling Device.destroy().

.on('cancel', handler(connection))

Twilio Client deviceに接続を受諾される前に着信接続がキャンセルされた時に発動します。


.on('connect', handler(connection))

This is triggered when a connection is opened, whether initiated using .connect() or via an accepted incoming connection.

ハンドラー関数は Twilio.Connection オブジェクトを引数に取ります。

.on('disconnect', handler(connection))

Fired any time a Connection is closed. The handler function receives the Twilio.Connection object that was just closed as an argument.

.on('error', handler(error))

Emitted when any device error occurs. These may be errors in your request, your 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.


プロパティ 概要
message エラーを説明する文字列です。
code Twilio クライアント エラー コード リファレンスに記載されているエラー コード番号です。
connection エラーが起きた際、Twilio.Connectionオブジェクトはアクティブであることを参考にして下さい。
twilioError When applicable, errors emitted now contain this twilioError field, providing more information about the error. This twilioError represents the new TwilioError format that will become the default Error format in the next major release of this SDK. To get a list of possible twilioErrors, please visit this page.
Twilio.Device.on('error', function(error) {

.on('incoming', handler(connection))

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 Access Token you provided in .setup(token). See the Client Quickstart on receiving incoming connections for more information.

ハンドラー関数は Twilio.Connection オブジェクトを引数に取ります。 この接続の状態は、.accept() するまでは pending となります。

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

.on('offline', function(device))

This is triggered when the connection to Twilio drops or the device's 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 will be fired, 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.

ハンドラー関数は、Twilio.Device オブジェクト 1 つだけを引数に取ります。


.on('ready', function(device))

This is initially triggered when all operations in .setup() have completed and the device is ready and online. It will be triggered again if the device goes offline and comes back online (i.e. the connection drops and returns).

ハンドラー関数は、Twilio.Device オブジェクト 1 つだけを引数に取ります。

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


Static Fields


Device.isSupported is a boolean value which indicates whether WebRTC is supported by the browser or not. If false, it's an indicator that Device.setup should not be called or else it will throw an unsupported exception.


Device.packageName returns the npm package name. This can be used to get the logger instance used by the SDK. See SDK Logger for details.


import { getLogger } from 'loglevel';
const logger = getLogger(Device.packageName);


Device.version returns the current version of the SDK.

Edge Fallback

By default, the SDK automatically reconnects the WebSocket connection to the same edge location when it is unreachable, or when the SDK encounters a network error that results in a WebSocket disconnect. But if Twilio.Device.Options.edge parameter is supplied as an array of edge names, the SDK will enable automatic Edge fallback functionality. The diagram below illustrates the logic that is executed to perform the fallback.


During initialization, the SDK will use the first edge name in the Twilio.Device.Options.edge array. If the SDK encounters an error that results in a WebSocket disconnect with error code 1006 or 1015, the SDK will attempt reconnection to the next Edge in the array using an exponential backoff timer with an initial value of 1+random(5) and a maximum of 20 seconds. This maximum delay can be configured via Twilio.Device.Options.backoffMaxMs parameter.

If the SDK encounters an error while already connected to an edge server, the SDK will try to reconnect to the same edge once before attempting to connect to the next edge.

The following table provides common scenarios for when a fallback may occur:

Scenario Expected Behavior
Initialize with edge: [“ashburn”] This behaves exactly the same as initializing with edge: “ashburn”. In this scenario, the SDK will always attempt to reconnect to ashburn whenever the WebSocket is disconnected.
The first edge name specified in the edge array is unreachable.

• ashburn becomes unreachable
• Initialize with edge: [“ashburn”, “sydney”]
The SDK will attempt to connect to ashburn. Since ashburn is unreachable, the attempt will fail. The SDK will then attempt to connect to sydney.
All edge endpoints are unreachable, then one region becomes available after a few seconds.

• ashburn, sydney, and dublin becomes unreachable
• Initialize with edge: [“ashburn”, “sydney”, “dublin”]
• sydney becomes available, and the rest of the regions are still unreachable
The SDK will attempt to connect to ashburn. Since ashburn is unreachable, the attempt will fail. The SDK will then attempt sydney and will fail again. Then dublin will be attempted and fail. Once the SDK reaches the last edge name, it will loop back to the first edge name ashburn, and will keep cycling through the edge names until one edge endpoint becomes available. If sydney becomes available, the SDK will be connected to sydney once the loop reaches it.
All edges are available and the edge the SDK is connected to suddenly becomes unreachable.

• Initialize with edge: [“ashburn”, “sydney”, “dublin”]
• SDK is now connected to ashburn.
• ashburn goes down and becomes unreachable
If you are connected to ashburn and it suddenly becomes unreachable, the SDK will attempt to connect to ashburn once. If the attempt fails, the SDK will attempt to connect to the next edge, which is sydney.

It’s important to note that “unreachable” in these scenarios means the SDK failed to establish a WebSocket connection to the edge endpoint which resulted in error code 1006 or 1015. The error code 1015 is a WebSocket close event which is raised when the connection fails to perform a TLS handshake. This happens if the server certificate is invalid or cannot be verified. While the error code 1006 is raised when the connection was dropped unexpectedly and there is no close frame received from the server. The following are common issues that causes 1006:

  • The domain name cannot be resolved by the DNS
  • The network cannot reach the endpoint due to, for example, a misconfigured firewall
  • The client becomes offline due to, for example, the local device losing network connectivity, and
  • In an unlikely and very rare scenario, the Edge and standby servers are down

SDK Logger

Prior to version 1.10.0, Voice Client JS logging could only be configured during Device.setup using debug and warnings flag. Starting 1.10.0, Voice Client JS exposes a loglevel based logger which allows for runtime logging configuration that includes setting the log level to “trace”, “debug”, “info”, “warn” and “error”. Loglevel is a versatile logger library that includes level-based logging and filtering, and provides a plugin API to enable functionality such as sending the log messages to a log server.

For example, to enable logging:

import { getLogger } from 'loglevel';

const logger = getLogger(Device.packageName);
// Set log level on subsequent page loads and refreshes


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.



Set the MediaTrackConstraints to be applied on every getUserMedia call for new input device audio. Any deviceId specified here will be ignored. Instead, device IDs should be specified using .audio.setInputDevice(). The returned Promise resolves when the media is successfully reacquired, or immediately if no input device is set.

device.audio.setAudioConstraints({ echoCancellation: true });
await device.audio.setInputDevice('default');
// Now we have a live input audio track, opened with echoCancellation:true
  autoGainControl: false,
  echoCancellation: false,
  noiseSuppression: false,
}).then(() => {
  // We successfully applied the new constraints and should automatically hear the difference.
  // Future calls to setInputDevice will also use these constraints until they're cleared.
}, err => {
  // Something went wrong, most likely err is an OverconstrainedError. Let's roll back.
  await device.audio.unsetAudioConstraints();
  // We should now have a working input audio track again


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.

メモ: これは、複数入力デバイスのサポートが欠如しているため、Firefox(51の最新版)ではサポートされていません。

Twilio.Device.audio.setInputDevice('default').then(function() {


Unset the MediaTrackConstraints to be applied on every getUserMedia call for new input device audio. The returned Promise resolves when the media is successfully reacquired, or immediately if no input device is set.


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

Twilio.Device.audio.unsetInputDevice().then(function() {



The currently set input audio MediaTrackConstraints set by setAudioConstraints(). Starts as null.


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 may contain auto-generated labels (e.g. “Unknown Audio Output Device 1”), or an incomplete / empty list of devices, until the user grants the application access to these resources in response to a call to the browser's getUserMedia() API. In an effort to reduce device fingerprinting, all major browsers are getting more strict in this regard. We strongly recommend your application calls getUserMedia() before rendering your input / output device selection UI for the cleanest user experience.

メモ: ユーザーからの許可が得られている場合でも、Firefox(執筆時の最新版は51)ではいかなるaudiooutputデバイスも一覧せず、Edge(執筆時の最新版は38)ではaudiooutputデバイスにラベル付けを行いません。

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

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


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 availableInDevices may contain auto-generated labels (e.g. “Unknown Audio Input Device 1”), or an incomplete / empty list of devices, until the user grants the application access to these resources in response to a call to the browser's getUserMedia() API. In an effort to reduce device fingerprinting, all major browsers are getting more strict in this regard. We strongly recommend your application calls getUserMedia() before rendering your input / output device selection UI for the cleanest user experience.

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


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


speakerDevices は標準スピーカーサウンド(通話の開始時に発信音、切断音、ユーザーがプッシュするDTMFトーン、および通話相手の音声)の再生にどの出力デバイスが使用されているかを制御するAudioOutputCollectionです。 この一連のデバイスを変更すると、これらのサウンドに使用されているデバイスが切り替わります。 通話中にこれらを変更すると、通話相手の音声は新しい出力セットで即座に再生されます。

メモ: これは、HTMLAudioElement.setSinkId()のサポートが不足しているため、Firefox(執筆時の最新バージョンは51)またはEdge(執筆時の最新のバージョン38)ではサポートされていません

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


ringtoneDevices は通話が着信した際の着信音の再生にどの出力デバイスが使用されているかを制御するAudioOutputCollectionです。 この一連のデバイスを変更すると、これらのサウンドに使用されているデバイスが切り替わります。

メモ: これは、HTMLAudioElement.setSinkId()のサポートが不足しているため、Firefox(執筆時の最新バージョンは51)またはEdge(執筆時の最新のバージョン38)ではサポートされていません

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...
// ... or test playback using a custom sound

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.

メモ: 入力デバイスを設定するための手段がサポートされないため、これはFirefox(執筆時の最新版は51)に含まれることはありません。


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.


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
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();
    speakerDevices.forEach(function(spkDev) {
        if (spkDev.deviceId === id) {
          deviceOption.setAttribute('selected', 'selected');


// 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'); });


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] ) 




.audio.outgoing( [bool] ) 




.audio.disconnect( [bool] ) 





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.

Additionally, Twilio Client is moving toward the standard EventEmitter interface, meaning events should be managed with .on(eventName, handler) and .removeListener(eventName, handler), replacing our legacy handlers (such as .accept(handler), .error(handler), etc...). The following methods are deprecated:


These have been replaced with the following events:

Device.on('cancel', handler)
Device.on('connect', handler)
Device.on('disconnect', handler)
Device.on('error', handler)
Device.on('incoming', handler)
Device.on('offline', handler)
Device.on('ready', handler)


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.



        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!


        Get link

        Get a free personal referral link here


        Give $10

        Your user signs up and upgrade using link


        Get $10

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