メニュー

Rate this page:

Thanks for rating this page!

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

twilio.jsライブラリー Twilio.Device

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

メソッドの参照

Twilio.Device

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) or Capability Token (deprecated, 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().

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 an 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.
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.
closeProtection false boolean もしくは string。このプロパティを true に設定すると、接続がアクティブであるページを閉じたときにテキスト"A call is currently in progress. Leaving or reloading this page will end the call." を表示するダイアログプロンプトが有効になります。string に設定するとメッセージプロンプトを変更できます。注:カスタムテキストをサポートしてないブラウザの場合、Twilio はブラウザのデフォルトメッセージを表示します。
debug false trueもしくはfalse。このプロパティをtrueに設定するとブラウザーのコンソールにデバッグが有効になります。
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.
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.
region gll 登録、通話の開始、電話の着信時に使用する Twilio データセンターを指定します。選択可能なリージョン、およびその IP アドレス範囲のリストについては、このページを参照してください。
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 trueもしくはfalsefalseに設定すると、廃止される予定のメソッドを呼び出した時ブラウザコンソールのロギングを無効にできます。

たとえば、次のようになります。

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

もしくは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'
  }
}

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

.setup()をコールし、Deviceのケイパビリティトークンに関連付けてられたアプリケーションに新しい接続を試行します。(詳しい情報はクライアントケイパビリティトークンをご覧ください

オプションparams引数は、POST/GETパラメーターとしてアプリケーションにパスされたJavascriptオブジェクトです。

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

例えば、下記のコードはagent=Smithと、location=Matrixをデバイスケイパビリティトークンに関連付けられたアプリケーションに渡します。

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

オプションで通話中にローカルメディアストリームの振る舞いを変更するためにaudioConstraintsオブジェクトを特定できます。マイクの選択、オートゲインコントロールのような機能のオフをすることに利用できます。それぞれのウェブブラウザーはaudioConstraintsとして使われる異なったMediaTrackConstraintsの組み合わせを実装しています。ブラウザの実装詳細に関してgetUserMediaに問い合わせて下さい。

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

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

.connect()メソッドはオブジェクトを返します。Twilio.Connectionオブジェクトを返します。.disconnect()使うことにより通話コネクションを終了できます。

VoiceUrl の TwiML の例

.connect()を読んだ時、クライアントはTwilio.Deviceケイパビリティトークンを使ってTwilioアプリケーションの新しい接続を試行します。
このアプリケーションは 電話・Clientへの発信、カンファレンスの開始、インタラクティブIVRを開始することができます。

例としてアプリケーションのVoiceUrlは下記のTwiMLを呼び出します。

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

その後デバイスは.connect()を呼ぶ度に415-867-5309に発信します。

すべてのTwiMLはクライアントアプリケーションで有効です。

アプリ用のTwiMLを動的に生成するためにparamsを使って.connect()のアプリケーションに渡すことができます。例として、下記のJavascriptのコードを実行できます。

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

TwiMLを生成、HTTPからphoneパラメーターを読み出すウェブアプリケーションは、下記の様にリクエストし、TwiMLに挿入します。

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

.activeConnection()

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

.destroy()

デバイスを破棄します。アクティブコネクションと保留されているコネクションを切断します。これにより、オフラインイベントハンドラーを発動します。Device.setup() が再度呼び出されるまで、デバイスは新しいコネクションを確立したり、受信したりできません。

.disconnectAll()

アクティブコネクションを切断します。disconnectイベントハンドラーを発動します。
新しい着信を防ぐことはできません。

.status()

デバイスのステータスを返します。ステータスは、次のいずれかの文字列になります。

ステータス名 概要
ready デバイスはTwilioに接続され、有効なケイパビリティトークンを持っています。
offline デバイスはTwilioに接続されておらず、ケイパビリティトークンの有効期限が切れているか、無効です。
busy デバイスはTwilioに接続されており、アクティブなコネクションを持っています。
着信を受け付けられないか、発信をしている最中です。

Events

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

This is triggered when an incoming connection is canceled by the caller before it is accepted by the Twilio Client device.

ハンドラー関数はTwilio.Connectionオブジェクトを引数として受け取ります。Connectionオブジェクトは有効でないコネクションを表すため、このイベントをアプリケーションのUIのアップデートに使用するでしょう。そしてConnectionをそのままにし次のコールを待ちます。

.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.

ハンドラー関数はerrorオブジェクトを引数に取ります。エラーオブジェクトは下記のパラメーターを持ちます。

プロパティ 概要
message エラーを説明する文字列です。
code Twilio クライアント エラー コード リファレンスに記載されているエラー コード番号です。
connection エラーが起きた際、Twilio.Connectionオブジェクトはアクティブであることを参考にして下さい。
Twilio.Device.on('error', function(error) {
  console.log(error.message);
});

.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) {
  connection.accept();
  // 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 つだけを引数に取ります。

アプリケーションを本番に移行する前に、offlineを実装に含めることを強く推奨いたします。

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

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

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

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

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.

メソッド

.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.

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

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.

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

プロパティ

.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.

メモ: ユーザーからの許可が得られている場合でも、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, ')');
});

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

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

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 は通話が着信した際の着信音の再生にどの出力デバイスが使用されているかを制御する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...
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.

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

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
使用例
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');
        }
    });

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

着信の際のイベント音を有効、無効にできます。

.audio.incoming() 

着信の際のイベント音が有効か無効かをbooleanで返します。

.audio.outgoing( [bool] ) 

発信の際のイベント音を有効、無効にできます。

.audio.outgoing() 

発信の際のイベント音が有効か無効かをbooleanで返します。

.audio.disconnect( [bool] ) 

切断の際のイベント音を有効、無効にできます。

.audio.disconnect() 

切断の際のイベント音が有効か無効かをbooleanで返します。

廃止予定のメソッド

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:

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

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