Skip to main content

Call

A Call object represents an active call. You can get instances of a Call object from a Voice.Client, by answering or initiating calls.

Examples

In this example, we are dialing a phone number and playing a TTS message.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

const call = await voiceClient.dialPhone({
from: "+YYYYYYYYYY",
to: "+XXXXXXXXXX"
});

await call.playTTS({ text: "Welcome to SignalWire!" });

In this example, we are answering an incoming call, playing a TTS message and then hanging up.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["topic"],
onCallReceived: async (call) => {
call.answer();
console.log("Call received", call.id);
await call.playTTS({ text: "Welcome to SignalWire!" });
call.hangup();
}
});

Properties

device
any

The device configuration for this call.

direction
"inbound" | "outbound"

Whether you are making or receiving the call.

from
string

The phone number that the call is coming from.

headers
SipHeader[]

Optional SIP headers for this call. See [SipHeader][types].

id
string

Unique ID for this voice call.

state
"created" | "ringing" | "answered" | "ending" | "ended"

The current state of the call.

to
string

The phone number you are attempting to call.

type
"phone" | "sip"

The type of call. Only phone and sip are currently supported.

Methods

amd

amd(params?): Promise<CallDetect>

Detects the presence of an answering machine. Alias for detectAnsweringMachine.


answer

answer(): Promise<Call>

Answers the incoming call.

Parameters

This method has no parameters.

Returns

Promise<Call>

Example

In this example, we answer an incoming call on the office topic.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["office"],
onCallReceived: (call) => {
call.answer();
console.log("Call received", call.id);
}
});

collect

collect(params): Promise<CallCollect>

Collect user input. For methods that include a prompt to the user, please see promptAudio, promptRingtone, or promptTTS.

Parameters

params
objectrequired

Object containing the parameters for collecting user input.

params.digits
CollectDigitsConfig

Configuration for collecting digits. You must either set this, or speech. See CollectDigitsConfig.

params.speech
CollectSpeechConfig

Configuration for collecting speech. You must either set this, or digits. See CollectSpeechConfig.

params.continuous
boolean
Default: false

Detect utterances and digits until stopped.

params.initialTimeout
number
Default: 4

Number of seconds to wait for initial input before giving up. Will be used only when startInputTimers is true or when the timer is started manually via the startInputTimers method.

params.partialResults
boolean
Default: false

If true, partial result events are fired.

params.sendStartOfInput
boolean
Default: false

If true, the startOfInput event is fired when input is detected.

params.startInputTimers
boolean
Default: false

If true, the initialTimeout timer is started.

params.listen
object

Callback to listen for events. List of collect events can be found here. Example event: onStarted.

Returns

Promise<CallCollect>

A promise that resolves to a CallCollect object that you can use to view the current state and results of the collect session.

Examples

Digits Example

In this example, we collect digits from the user and log the result.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
call.answer();
console.log("Call received", call.id);
let collectResult = await call.collect({
digits: {
max: 5,
digitTimeout: 2,
terminators: "#*"
}
}).onStarted();
const { type, digits, terminator } = await collectResult.ended();
console.log("Collected", type, digits, terminator);
call.hangup();
}
});
Speech Example

In this example, we collect speech from the user and log the result.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
call.answer();
console.log("Call received", call.id);
let collectResult = await call.collect({
speech: {
endSilenceTimeout: 2,
speechTimeout: 10,
language: "en-US",
hints: ["sales", "support", "representative"]
}
}).onStarted();
const { type, speech } = await collectResult.ended();
console.log("Collected", type, speech);
}
});
CallCollect Events Example

In this example we are collecting digits and listening for results using the CallCollect Events:

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Setup a Voice Client and listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
call.answer();
console.log("Call received", call.id);

// Start a call collect session
await call.collect({
digits: {
max: 4,
digitTimeout: 10,
terminators: "#"
},
partialResults: true,
sendStartOfInput: true,
listen: {
onStarted: () => {
console.log("Collect started");
},
onInputStarted: (collect) => {
console.log("Collect input started:", collect.result);
},
onUpdated: (collect) => {
console.log("Collect updated:", collect.result);
},
onFailed: (collect) => {
console.log("Collect failed:", collect.result);
},
onEnded: async (collect) => {
console.log("Collect ended:", collect.result);

// Play back the digits collected
await call.playTTS({ text: `You entered ${collect.digits}` });
call.hangup()
}
}
}).onStarted();
}
});

connect

connect(params): Promise<Call>

Attempt to connect an existing call to a new outbound call. The two devices will hear each other. You can wait until the new peer is disconnected by calling disconnected.

This is a generic method that allows you to connect to multiple devices in series, parallel, or combinations of both with the use of a DeviceBuilder.

tip

For simpler use cases, we recommend using connectPhone or connectSip.

Parameters

params
objectrequired

Object containing the parameters for connecting the call.

params.devices
VoiceDeviceBuilderrequired

A device builder specifying the devices to call. See VoiceDeviceBuilder.

params.ringback
VoicePlaylist

Ringback audio to play to the first call leg. You can play audio, TTS, silence or ringtone. See VoicePlaylist.

params.maxPricePerMinute
number

The maximum price in USD acceptable for the call to be created. If the rate for the call is greater than this value, the call will not be created. If not set, all calls will be created. Price can have a maximum of four decimal places, i.e. 0.0075.

Returns

Promise<Call>

A promise that resolves to a Call object that you can use to control the new peer. The promise resolves only after the new peer picks up the call.

Examples

Connecting to a new SIP call, while playing ringback audio to the first leg of the call.

import { SignalWire, Voice} from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

const ringback = new Voice.Playlist().add(
Voice.Playlist.Ringtone({
name: "it"
})
);

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {

let plan = new Voice.DeviceBuilder().add(
Voice.DeviceBuilder.Sip({
// Replace the to and from with valid SIP endpoint domains
from: `sip:${call.from}@example.sip.signalwire.com`,
to: "sip:example@example.sip.signalwire.com",
timeout: 30
})
);
// Answer the call
call.answer();
// Connect the call to the device builder plan
const peer = await call.connect({
devices: plan,
ringback: ringback
});
// Listen to peer state changes
await peer.listen({
onStateChanged: (state) => {
console.log("Peer state changed:", state.state);
}
})
// wait for peer to hangup
await peer.disconnected();
console.log("The peer hungup");
// hangup the call
call.hangup();
}
});

connectPhone

connectPhone(params): Promise<Call>

Attempt to connect an existing call to a new outbound phone call. The two devices will hear each other. You can wait until the new peer is disconnected by calling disconnected.

Parameters

params
objectrequired

Object containing the parameters for connecting the call to a phone number.

params.to
stringrequired

The party you are attempting to call.

params.from
string

The party the call is coming from. Must be a SignalWire number or SIP endpoint that you own.

params.timeout
number

The time, in seconds, the call will ring before it is considered unanswered.

params.maxPricePerMinute
number

The maximum price in USD acceptable for the call to be created. If the rate for the call is greater than this value, the call will not be created. If not set, all calls will be created. Price can have a maximum of four decimal places, i.e. 0.0075.

params.ringback
VoicePlaylist

Ringback audio to play to the call leg. You can play audio, TTS, silence or ringtone. See VoicePlaylist.

params.callStateUrl
string

Webhook URL to which SignalWire will send call status change notifications. See the payload specifications under CallState.

params.callStateEvents
string[]
Default: ["ended"]

An array of event names to be notified about. Allowed values are created, ringing, answered, and ended.

Returns

Promise<Call>

A promise that resolves to a Call object that you can use to control the new peer. The promise resolves only after the new peer picks up the call.

Example

In this example, we connect an inbound call to an outbound phone number. We play a ringback tone to the inbound call leg while waiting for the outbound phone number to answer. Once the outbound phone number answers, we wait for the peer to hangup and then hangup the inbound leg of the call.

import { SignalWire, Voice} from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;
// Ringback tone
const ringback = new Voice.Playlist().add(
Voice.Playlist.Ringtone({
name: "it"
})
);

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {

// Answer the call
call.answer();
// Connect the call to the device builder plan
let peer = await call.connectPhone({
// Replace the to parameter with a valid phone number
to: "+1XXXXXXXXXX",
from: call.from,
ringback: ringback
});

// Listen to peer state changes
await peer.listen({
onStateChanged: (state) => {
console.log("Peer state changed:", state.state);
}
})
// wait for peer to hangup
await peer.disconnected();
console.log("The peer hungup");
// hangup the call
call.hangup();
}
});

connectSip

connectSip(params): Promise<Call>

Attempt to connect an existing call to a new outbound SIP call. The two devices will hear each other. You can wait until the new peer is disconnected by calling disconnected.

Parameters

params
objectrequired

Object containing the parameters for connecting the call to a SIP endpoint.

params.from
stringrequired

The party the call is coming from. Must be a SignalWire number or SIP endpoint that you own.

params.to
stringrequired

The party you are attempting to call.

params.timeout
number

The time, in seconds, the call will ring before it is considered unanswered.

params.headers
SipHeader[]

Array of SipHeader objects. Must be X- headers only, see example below.

params.codecs
SipCodec[]

Array of desired codecs in order of preference. Supported values are PCMU, PCMA, OPUS, G729, G722, VP8, H264. Default is parent leg codec(s). See SipCodec.

params.webrtcMedia
boolean

If true, WebRTC media is negotiated. Default is parent leg setting.

params.sessionTimeout
number

Non-negative value, in seconds, to use for the SIP Session-Expires header. If 0 or unset, SignalWire will pick the default (typically 600).

params.maxPricePerMinute
number

The maximum price in USD acceptable for the call to be created. If the rate for the call is greater than this value, the call will not be created. If not set, all calls will be created. Price can have a maximum of four decimal places, i.e. 0.0075.

params.ringback
VoicePlaylist

Ringback audio to play to the call leg. You can play audio, TTS, silence or ringtone. See VoicePlaylist.

params.callStateUrl
string

Webhook URL to which SignalWire will send call status change notifications. See the payload specifications under CallState.

params.callStateEvents
string[]
Default: ["ended"]

An array of event names to be notified about. Allowed values are created, ringing, answered, and ended.

Returns

Promise<Call>

A promise that resolves to a Call object that you can use to control the new peer. The promise resolves only after the new peer picks up the call.

Example

In this example, we connect a inbound call to a internal SIP endpoint. We play a ringback tone to the inbound call leg while waiting for the SIP endpoint to answer. Once the SIP endpoint answers, we wait for the peer to hangup and then hangup the inbound call.

import { SignalWire, Voice} from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;
// Ringback tone
const ringback = new Voice.Playlist().add(
Voice.Playlist.Ringtone({
name: "it"
})
);

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {

// Answer the call
call.answer();
// Connect the call to the device builder plan
let peer = await call.connectSip({
// Replace the to and from with valid SIP endpoint domains
to: "sip:example@example.sip.signalwire.com",
from: `sip:${call.from}@example.sip.signalwire.com`,
ringback: ringback
});

// Listen to peer state changes
await peer.listen({
onStateChanged: (state) => {
console.log("Peer state changed:", state.state);
}
})
// wait for peer to hangup
await peer.disconnected();
console.log("The peer hungup");
// hangup the call
call.hangup();
}
});

detect

detect(params): Promise<CallDetect>

Generic method. Please see amd, detecFax, and detectDigit.

Parameters

params
objectrequired

Object containing the parameters for detection.

params.type
"fax" | "machine" | "digit" | "beep"required

The type of detection to perform:

Returns

Promise<CallDetect>

A promise that resolves to a CallDetect object that you can use to view the current state and results of the detect session.


detectAnsweringMachine

detectAnsweringMachine(params?): Promise<CallDetect>

Detects the presence of an answering machine.

Parameters

params
object

Object containing the parameters for answering machine detection.

params.timeout
number
Default: 30.0

Number of seconds to run the detector for.

params.waitForBeep
boolean
Default: false

Whether to wait until the device is ready for voicemail delivery.

params.initialTimeout
number
Default: 4.5

Number of seconds to wait for initial voice before giving up.

params.endSilenceTimeout
number
Default: 1.0

Number of seconds to wait for voice to finish.

params.machineReadyTimeout
number

Number of seconds to wait for voice to finish before firing the READY event. Default is the value of endSilenceTimeout.

params.machineVoiceThreshold
number
Default: 1.25

How many seconds of voice to decide it is a machine.

params.machineWordsThreshold
number
Default: 6

How many words to count to decide it is a machine.

params.detectInterruptions
boolean
Default: false

If set to true, a NOT_READY event is fired if speech is detected after the READY event. This allows the application to restart message delivery to the answering machine.

params.listen
object

Callback to listen for events. List of detect events can be found here. Example event: onStarted.

Returns

Promise<CallDetect>

A promise that resolves to a CallDetect object that you can use to view the current state and results of the detect session.

Example

In this example, we dial a phone number and wait for the answering machine detection to finish. Once the detection is finished, we log the result and then play a TTS message. At the end of the TTS message, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

try {
// Outbound Dial
const call = await voiceClient.dialPhone({
from: "SignalWire From Number Here",
to: "Destination Number Here",
timeout: 30,
listen: {
onStateChanged: (call) => {
console.log("Call state changed:", call.state);
}
}
});

// Answering machine detection
await call.detectAnsweringMachine({
waitForBeep: true,
endSilenceTimeout: 4,
listen: {
onStarted: () => {
console.log("Answering machine detection started");
},
onUpdated: (event) => {
console.log("Answering machine detection updated:", event.result);
},
onEnded: async (event) => {
console.log("Answering machine detection ended:", event.result);
}
}
});
// Plays a TTS message after the answering machine detection is finished.
// Then the Call will hangup after the TTS message is finished.
await call.playTTS({ text: "Hello, this is a test call from SignalWire!" });
call.hangup();
} catch (e) {
console.log("Call not answered.", e);
}

detectDigit

detectDigit(params?): Promise<CallDetect>

Detects when a digit is pressed in an audio stream. To gather digit input from a caller, please see prompt.

Parameters

params
object

Object containing the parameters for digit detection.

params.digits
string
Default: 0123456789#*

The digits to detect.

params.timeout
number
Default: 30.0

Number of seconds to run the detector for.

params.waitForBeep
boolean
Default: false

Whether to wait until the device is ready for voicemail delivery.

params.listen
object

Callback to listen for events. List of detect events can be found here. Example event: onStarted.

Returns

Promise<CallDetect>

A promise that resolves to a CallDetect object that you can use to view the current state and results of the detect session.

Example

In this example, we dial a phone number and wait for the digit detection to finish. Once the detection is finished, we log the result and then play a TTS message of the digit pressed and then hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {

// Answer the call
call.answer();
await call.detectDigit({
listen: {
onStarted: () => console.log("Detection started!"),
onEnded: (detect) => console.log("Finished detecting digit", detect.result),
onUpdated: async (detect) => {
console.log("Updated detecting digit", detect.result)
// Stop the detection and play the digit pressed
detect.stop();
await call.playTTS({ text: `You pressed ${detect.result})` });
call.hangup();
}
}
}).onStarted();
}
});

detectFax

detectFax(params?): Promise<CallDetect>

Detects the presence of a fax machine.

Parameters

params
object

Object containing the parameters for fax detection.

params.timeout
number
Default: 30.0

Number of seconds to run the detector for.

params.tone
"CED" | "CNG"
Default: CED

The fax tone to detect: CED or CNG.

params.waitForBeep
boolean
Default: false

Whether to wait until the device is ready for voicemail delivery.

params.listen
object

Callback to listen for events. List of detect events can be found here. Example event: onStarted.

Returns

Promise<CallDetect>

A promise that resolves to a CallDetect object that you can use to view the current state and results of the detect session.

Example

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Setup a voice client tolisten for incoming calls
await voiceClient.listen({
topics: ['office'],
onCallReceived: async (call) => {
// Answer the call
console.log("Call received");
call.answer();
// Fax detection
await call.detectFax({
tone: 'CNG',
listen: {
onStarted: () => {
console.log("Fax detection started");
},
onUpdated: (event) => {
console.log("Fax detection updated:", event.result);
},
onEnded: (event) => {
console.log("Fax detection finished:", event.result);
call.hangup();
}
}
}).onStarted()
}
})

disconnect

disconnect(): Promise<void>

Disconnects the connected peer from the call.

Returns

Promise<void>

Example

In this example, we answer an incoming call and connect the call to a peer call. Once connected to the peer, we play a TTS message to the peer and then disconnect the peer. Once the peer is disconnected, we play a TTS message to the inbound call leg and then hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ['office'],
onCallReceived: async (call) => {
// Answer the call
call.answer();
// Connect call to a new peer
let peer = await call.connectPhone({
from: call.from,
to: "Destination Number Here"
})
// Play TTS to the peer
await peer.playTTS({ text: 'Hello from SignalWire!' });
// Disconnect the peer call
call.disconnect();
await call.playTTS({ text: 'Disconnecting Peer!' });
console.log("The Peer and Call have been disconnected, but the calls are still active.")
// Hangup the peer call
await peer.playTTS({ text: 'Ending Peer Session' });
peer.hangup();
// Hangup the call
await call.playTTS({ text: 'Ending Call Session' });
call.hangup();
}
})

disconnected

disconnected(): Promise<Call>

Call this method after connecting a peer (e.g., using connect, connectPhone, or connectSip) to wait until the peer disconnects.

This is equivalent to calling peer.waitFor("ended") on the connected peer.

Returns

Promise<Call>

A promise that resolves to the Call object that you can use to control the call.

Example

In this example, we answer an incoming call and connect the call to a peer call. After connecting to the peer, we wait 3 seconds and then disconnect the peer. Once the peer is disconnected, we play a TTS message to the inbound call leg and then hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ['office'],
onCallReceived: async (call) => {
// Answer the call
call.answer();
// Connect call to a new peer
let peer = await call.connectPhone({
from: call.from,
to: "Destination Number Here",
})

// wait 3 seconds then disconnect the peer
setTimeout(() => {
console.log('Disconnecting Peer');
peer.hangup();
}, 3000);

await call.disconnected();

await call.playTTS({ text: 'Peer disconnected, ending call.' });
call.hangup();
}
})

hangup

hangup(reason?): Promise<void>

Hangup the call.

Parameters

reason
"error" | "hangup" | "cancel" | "busy" | "noAnswer" | "decline"
Default: hangup

Reason for hanging up.

Returns

Promise<void>

Example

In this example, we listen for an incoming call and then hangup right away with a reason of busy.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
// Listen for a status change event on the call
await call.listen({
onStateChanged: (call) => {
console.log("Call state changed:", call.state);
}
})
// Hangup the call
await call.hangup("busy");
}
});

listen

listen({ event: Callback }): Promise<[Call Events][here]>

Listen for events on the call.

Parameters

listeners
objectrequired

Object containing event listener callbacks.

listeners.EVENT
Callback

The event to listen for. List of events can be found here. Example event: onStateChanged.

Returns

Promise<Call Events>

A promise that resolves to an unsubscribe function that you can call to stop listening for events.

Example

In this example, we listen for an incoming call and listen for the onStateChanged event. After 3 seconds, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

// Initialize the SignalWire client
const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

// Access video client from the main client
const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
// Answer the call
call.answer();
// Listen for a status change event on the call
await call.listen({
onStateChanged: (call) => {
console.log("Call state changed:", call.state);
}
})
// wait 3 seconds and then hangup
setTimeout(async () => {
await call.hangup();
}, 3000);
}
});

pass

pass(params): Promise<Call>

This will allow a client to decline incoming calls without ending the call and redirect the call to another Voice client.

Will trigger on the onCallReceived event.

Returns

Promise<Call>

A promise that resolves to the Call object that you can use to control the call.

Example

In this example, we listen for an incoming call and then pass the call to a different topic.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

await voiceClient.listen({
topics: ["office"],
onCallReceived: (call) => {
// pass the call to a different client
call.pass();
}
});

play

play(params): Promise<CallPlayback>

Play one or multiple media in a Call and waits until the playing has ended.

The play method is a generic method for all types of media, see playAudio, playSilence, playTTS or playRingtone for more specific usages.

Parameters

params
objectrequired

Object containing the parameters for playing media.

params.playlist
VoicePlaylistrequired

A media playlist. See VoicePlaylist.

params.listen
object

Callback to listen for events. List of playback events can be found here. Example event: onStarted.

Returns

Promise<CallPlayback>

A promise that resolves to a CallPlayback object that you can use to view the current state and results of the play session.

Example

In this example, we dial a phone number and play a TTS message. Once the TTS message is finished playing, we then play silence on the call for 1 second and then play an audio file. Once the audio file is finished playing, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call and play a TTS message using the generic play method, then play silence for 1 second, then play an audio file.
call.answer();
const playlist = new Voice.Playlist({ volume: 1.0 })
.add(Voice.Playlist.TTS({
text: 'Welcome to SignalWire!'
}))
.add(Voice.Playlist.Silence({ duration: 1 }))
.add(Voice.Playlist.Audio({
url: 'https://cdn.signalwire.com/default-music/welcome.mp3'
}))
await call.play({
playlist: playlist,
listen: {
onStarted: () => console.log('Playback started!'),
onFailed: (playback) => console.log('Playback failed', playback.state),
onUpdated: (playback) => console.log('Playback state is:', playback.state),
onEnded: (playback) => {
console.log('Playback ended', playback.state);
// Hangup the call
call.hangup();
},
}
}).onStarted();
}
});

playAudio

playAudio(params): Promise<CallPlayback>

Plays an audio file.

Parameters

params
objectrequired

Object containing the parameters for playing audio.

params.url
stringrequired

HTTP(s) URL to an audio resource to play.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of playback events can be found here. Example event: onStarted.

Returns

Promise<CallPlayback>

A promise that resolves to a CallPlayback object that you can use to view the current state and results of the play session.

Example

In this example, we dial a phone number and play an audio file. Once the audio file is finished playing, we hangup the call. We also listen for playback events.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call and play an audio file. Listens for playback events. Ends the call after the audio file is finished playing.
call.answer();
await call.playAudio({
url: "https://cdn.signalwire.com/default-music/welcome.mp3",
listen: {
onStarted: () => console.log("Started playing"),
onFailed: () => console.log("Failed to play"),
onUpdated: (event) => console.log("Updated playing", event.state),
onEnded: (event) => {
console.log("Ended playing", event.state);
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

playRingtone

playRingtone(params): Promise<CallPlayback>

Plays a ringtone.

Parameters

params
objectrequired

Object containing the parameters for playing a ringtone.

params.name
RingtoneNamerequired

The name of the ringtone. See RingtoneName.

params.duration
number

Duration of ringtone to play in seconds. Defaults to 1 ringtone iteration.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of playback events can be found here. Example event: onStarted.

Returns

Promise<CallPlayback>

A promise that resolves to a CallPlayback object that you can use to view the current state and results of the play session.

Example

In this example, we dial a phone number and play a ringtone for a duration of 10 seconds. Once the ringtone is finished playing, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call and play a ringtone. Listens for playback events. Ends the call after the ringtone is finished playing for 10 seconds.
call.answer();
await call.playRingtone({
duration: 10,
name: "it",
listen: {
onStarted: () => console.log("Ringtone started"),
onFailed: () => console.log("Ringtone failed"),
onUpdated: (event) => console.log("Ringtone updated", event.state),
onEnded: (event) => {
console.log("Ringtone ended", event);
call.hangup();
}
}
}).onStarted();
}
});

playSilence

playSilence(params): Promise<CallPlayback>

Plays some silence.

Parameters

params
objectrequired

Object containing the parameters for playing silence.

params.duration
numberrequired

Seconds of silence to play.

params.listen
object

Callback to listen for events. List of playback events can be found here. Example event: onStarted.

Returns

Promise<CallPlayback>

A promise that resolves to a CallPlayback object that you can use to view the current state and results of the play session.

Example

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play Silence on the call for a duration of 3 seconds. Listens for playback events. Ends the call after the silence is finished playing.
await call.playSilence({
duration: 3,
listen: {
onStarted: () => console.log("Silence started"),
onFailed: () => console.log("Silence failed"),
onUpdated: (event) => console.log("Silence updated", event.state),
onEnded: (event) => {
console.log("Silence ended", event.state);
call.hangup();
}
}
}).onStarted();
}
});

playTTS

playTTS(params): Promise<CallPlayback>

Plays text-to-speech.

Parameters

params
objectrequired

Object containing the parameters for playing text-to-speech.

params.text
stringrequired

Text to play. SSML may be entered as a string wrapped in <speak> tags. See our supported voices and languages documentation for usage and supported tags.

params.language
string
Default: en-US

Language of the text in ISO 639-1 (language name) + ISO 3166 (country code). Supported languages can be found here.

params.gender
"male" | "female"
Default: female

Gender of the voice.

params.voice
string

Voice to use (takes precedence over gender). Supported voices can be found here.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of playback events can be found here. Example event: onStarted.

Returns

Promise<CallPlayback>

A promise that resolves to a CallPlayback object that you can use to view the current state and results of the play session.

Examples

In this example, we dial a phone number and play a TTS message. Once the TTS message is finished playing, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.playTTS({
text: "Hello, this is a test call from SignalWire",
listen: {
onStarted: () => console.log("TTS started"),
onFailed: () => console.log("TTS failed"),
onUpdated: (tts) => console.log("TTS state:", tts.state),
onEnded: () => {
console.log("TTS ended");
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

In this example, we are using SSML to play a TTS message. Once the TTS message is finished playing, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call using SSML. Listens for playback events. Ends the call after the TTS is finished playing.
await call.playTTS({
text: `<speak>
Here are <say-as interpret-as="characters">SSML</say-as> samples.
I can pause <break time="3s"/>.
I can speak in cardinals. Your number is <say-as interpret-as="cardinal">10</say-as>.
Or I can speak in ordinals. You are <say-as interpret-as="ordinal">10</say-as> in line.
Or I can even speak in digits. The digits for ten are <say-as interpret-as="characters">10</say-as>.
I can also substitute phrases, like the <sub alias="World Wide Web Consortium">W3C</sub>.
Finally, I can speak a paragraph with two sentences.
<p><s>This is sentence one.</s><s>This is sentence two.</s></p>
</speak>
`,
voice: "polly.Joey",
listen: {
onStarted: () => console.log("TTS started"),
onFailed: () => console.log("TTS failed"),
onUpdated: (tts) => console.log("TTS state:", tts.state),
onEnded: () => {
console.log("TTS ended");
call.hangup();
}
}
}).onStarted();
}
});

prompt

prompt(params): Promise<CallPrompt>

Generic method to prompt the user for input.

info

Take a look at promptAudio, promptRingtone, or promptTTS for the more specific input methods.

Parameters

params
objectrequired

Object containing the parameters for prompting the user for input.

params.playlist
VoicePlaylistrequired

A media playlist to play. See VoicePlaylist.

params.digits
CollectDigitsConfig

Configuration for collecting digits. You must either set this, or speech. See CollectDigitsConfig.

params.speech
CollectSpeechConfig

Configuration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration. See CollectSpeechConfig.

params.initialTimeout
number
Default: 4

Initial timeout in seconds.

params.listen
object

Callback to listen for events. List of prompt events can be found here. Example event: onStarted.

Returns

Promise<CallPrompt>

A promise that resolves to a CallPrompt object that you can use to view the current state and results of the prompt session.

Examples

Digits Example

In this example, we dial a phone number and prompt for digits. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup. We also listen for prompt events.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Prompt for digits. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.
await call.prompt({
playlist: new Voice.Playlist().add(
Voice.Playlist.TTS({ text: "Please enter your PIN number."})
),
digits: {
max: 4,
digitTimeout: 10,
terminators: "#*"
},
listen: {
onStarted: () => console.log("Prompt started!"),
onFailed: () => console.log("Prompt failed!"),
onUpdated: (promptResult) => console.log("Prompt updated!", promptResult.result),
onEnded: (promptResult) => {
console.log("Prompt ended!", promptResult.result);
call.hangup();
}
}
}).onStarted();
}
});

Speech Example

In this example, we dial a phone number and prompt for speech. After the speech is entered or a timeout occurs, the call will hangup. We also listen for prompt events.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Prompt for speech. After the speech is entered or a timeout occurs, the call will hangup.
await call.prompt({
playlist: new Voice.Playlist().add(
Voice.Playlist.TTS({ text: "Please enter your PIN number."})
),
speech: {
model: "enhanced.phone_call"
},
listen: {
onStarted: () => console.log("Prompt started!"),
onFailed: () => console.log("Prompt failed!"),
onUpdated: (promptResult) => console.log("Prompt updated!", promptResult.result),
onEnded: (promptResult) => {
console.log("Prompt ended!", promptResult.result);
call.hangup();
}
}
}).onStarted();
}
});

promptAudio

promptAudio(params): Promise<CallPrompt>

Play an audio while collecting user input from the call, such as digits or speech.

Parameters

params
objectrequired

Object containing the parameters for prompting the user for input while playing audio.

params.url
stringrequired

HTTP(s) URL to an audio resource to play.

params.digits
CollectDigitsConfig

Configuration for collecting digits. You must either set this, or speech. See CollectDigitsConfig.

params.speech
CollectSpeechConfig

Configuration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration. See CollectSpeechConfig.

params.initialTimeout
number
Default: 4

Initial timeout in seconds.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of prompt events can be found here. Example event: onStarted.

Returns

Promise<CallPrompt>

A promise that resolves to a CallPrompt object that you can use to view the current state and results of the prompt session.

Examples

Digits Example

In this example, we dial a phone number and prompt for digits while playing audio in the background. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play audio on the call while prompting for digits. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.
await call.promptAudio({
url: "https://cdn.signalwire.com/default-music/welcome.mp3",
digits: {
max: 4,
digitTimeout: 10,
terminators: "#*"
},
listen: {
onStarted: () => console.log("Prompt started!"),
onFailed: () => console.log("Prompt failed!"),
onUpdated: (promptResult) => console.log("Prompt updated!", promptResult.result),
onEnded: (promptResult) => {
console.log("Prompt ended!", promptResult.result);
call.hangup();
}
}
}).onStarted();
}
});

Speech Example

In this example, we dial a phone number and prompt for speech while playing audio in the background. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptAudio({
url: "https://cdn.signalwire.com/default-music/welcome.mp3",
speech: {
model: "enhanced.phone_call",
},
listen: {
onStarted: () => console.log("Prompt started!"),
onFailed: () => console.log("Prompt failed!"),
onUpdated: (promptResult) => console.log("Prompt updated!", promptResult.result),
onEnded: (promptResult) => {
console.log("Prompt ended!", promptResult.result);
call.hangup();
}
}
}).onStarted();
}
});

promptRingtone

promptRingtone(params): Promise<CallPrompt>

Play a ringtone while collecting user input from the call, such as digits or speech.

Parameters

params
objectrequired

Object containing the parameters for prompting the user for input while playing a ringtone.

params.name
RingtoneNamerequired

The name of the ringtone. See RingtoneName.

params.digits
CollectDigitsConfig

Configuration for collecting digits. You must either set this, or speech. See CollectDigitsConfig.

params.speech
CollectSpeechConfig

Configuration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration. See CollectSpeechConfig.

params.duration
number

Duration of ringtone to play in seconds. Defaults to 1 ringtone iteration.

params.initialTimeout
number
Default: 4

Initial timeout in seconds.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of prompt events can be found here. Example event: onStarted.

Returns

Promise<CallPrompt>

A promise that resolves to a CallPrompt object that you can use to view the current state and results of the prompt session.

Examples

Digits Example

In this example, we dial a phone number and prompt for digits while playing a ringtone in the background. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptRingtone({

name: "it",
duration: 10,
digits: {
max: 5,
digitTimeout: 5,
terminators: "#*",
},
listen: {
onStarted: () => console.log("Prompt Ringtone started"),
onFailed: () => console.log("Prompt Ringtone failed"),
onUpdated: (event) => console.log("Prompt Ringtone updated", event.result),
onEnded: (event) => {
console.log("Prompt Ringtone ended", event.result);
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

Speech Example

In this example, we dial a phone number and prompt for speech while playing a ringtone in the background. After the ringtone ends, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptRingtone({

name: "it",
duration: 10,
speech: {
model: "enhanced.phone_call"
},
listen: {
onStarted: () => console.log("Prompt Ringtone started"),
onFailed: () => console.log("Prompt Ringtone failed"),
onUpdated: (event) => console.log("Prompt Ringtone updated", event.result),
onEnded: (event) => {
console.log("Prompt Ringtone ended", event.result);
// Hangup the call
call.hangup();
}
}
}).onStarted()
}
});

promptTTS

promptTTS(params): Promise<CallPrompt>

Play text-to-speech while collecting user input from the call, such as digits or speech.

Parameters

params
objectrequired

Object containing the parameters for prompting the user for input while playing text-to-speech.

params.text
stringrequired

Text to play. SSML may be entered as a string wrapped in <speak> tags. See our supported voices and languages documentation for usage and supported tags.

params.digits
CollectDigitsConfig

Configuration for collecting digits. You must either set this, or speech. See CollectDigitsConfig.

params.speech
CollectSpeechConfig

Configuration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration. See CollectSpeechConfig.

params.language
string
Default: en-US

Language of the text in ISO 639-1 (language name) + ISO 3166 (country code). Supported languages can be found here.

params.gender
"male" | "female"
Default: female

Gender of the voice.

params.voice
string

Voice to use (takes precedence over gender). Supported voices can be found here.

params.initialTimeout
number
Default: 4

Initial timeout in seconds.

params.volume
number
Default: 0

Volume value between -40dB and +40dB where 0 is unchanged.

params.listen
object

Callback to listen for events. List of prompt events can be found here. Example event: onStarted.

Returns

Promise<CallPrompt>

A promise that resolves to a CallPrompt object that you can use to view the current state and results of the prompt session.

Examples

Digits Example

In this example, we dial a phone number and prompt for digits while playing TTS in the background. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptTTS({
text: "Please enter your 5 digit pin number.",
duration: 10,
digits: {
max: 5,
digitTimeout: 5,
terminators: "#*",
},
listen: {
onStarted: () => console.log("Prompt TTS started"),
onFailed: () => console.log("Prompt TTS failed"),
onUpdated: (event) => console.log("Prompt TTS updated", event.result),
onEnded: (event) => {
console.log("Prompt TTS ended", event.result);
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

Speech Example

In this example, we dial a phone number and prompt for speech while playing TTS in the background. After the user speaks or a timeout occurs, the prompt session will end and return the speech results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptTTS({
text: "Please say your name.",
duration: 10,
speech: {
model: "enhanced.phone_call"
},
listen: {
onStarted: () => console.log("Prompt TTS started"),
onFailed: () => console.log("Prompt TTS failed"),
onUpdated: (event) => console.log("Prompt TTS updated", event.result),
onEnded: (event) => {
console.log("Prompt TTS ended", event.result)
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

SSML Example

In this example, we are using SSML to play a TTS message. We dial a phone number and prompt for digits while playing TTS in the background. After the digits are entered or a timeout occurs, the prompt session will end and return the digits results, and the call will hangup.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();
// Play TTS on the call
await call.promptTTS({
text: `<speak>
Please enter your <say-as interpret-as="characters">UUID</say-as>.
It should be a <say-as interpret-as="cardinal">5</say-as> digit number.
</speak>`,
voice: "polly.Joey",
duration: 20,
digits: {
max: 5,
digitTimeout: 20,
terminators: "#*",
},
listen: {
onStarted: () => console.log("Prompt TTS started"),
onFailed: () => console.log("Prompt TTS failed"),
onUpdated: (event) => console.log("Prompt TTS updated", event.result),
onEnded: (event) => {
console.log("Prompt TTS ended", event.result)
// Hangup the call
call.hangup();
}
}
}).onStarted();
}
});

record

record(params): Promise<CallRecording>

Generic method to record a call.

tip

Please use recordAudio.

Parameters

params
objectrequired

Object containing the parameters for recording the call.

params.audio
objectrequired

Audio recording configuration. See the parameters for recordAudio.

params.listen
object

Callback to listen for events. List of recording events can be found here. Example event: onStarted.

Returns

Promise<CallRecording>

A promise that resolves to a CallRecording object that you can use to view the current state and results of the recording session.

Example

In this example, we dial a phone number and record the call audio. During the recording, we play a TTS message. Once the TTS message is finished, we hangup the call and print the URL of the recording to console.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();

await call.record({
audio: {
format: "mp3",
direction: "both",
stereo: true,
beep: true,
terminators: "#",
endSilenceTimeout: 0,
initialTimeout: 0
},
listen: {
onStarted: async (recording) => {
console.log("Recording started");
await call.playTTS({
text: "This is a call recording test."
});
recording.stop();
},
onFailed: () => console.log("Recording failed"),
onUpdated: (event) => console.log("Recording updated", event.state),
onEnded: (event) => {
console.log("Recording ended", event.url, event.state)
call.hangup();
}
}
}).onStarted();
}
});

recordAudio

recordAudio(params?): Promise<CallRecording>

Records the audio from the call.

Parameters

params
object

Object containing the parameters for recording audio.

params.beep
boolean
Default: false

Whether to play a beep before recording.

params.format
"mp3" | "wav"
Default: mp3

Format of the recording.

params.stereo
boolean
Default: false

Whether to record in stereo mode.

params.direction
"listen" | "speak" | "both"
Default: speak

Direction to record. Can be listen (what the caller hears), speak (what the caller says), or both.

params.initialTimeout
number
Default: 5.0

How long to wait (in seconds) until something is heard in the recording. Disable by passing 0.

params.endSilenceTimeout
number
Default: 1.0

How long to wait (in seconds) until the caller has stopped speaking. Disable by passing 0.

params.terminators
string
Default: #*

DTMF digits that, when dialed, will end the recording.

params.inputSensitivity
number
Default: 44

Controls how sensitive the voice activity detector is to background noise, where 0 is least sensitive (hear nothing) and 100 is most sensitive (hear everything).

params.listen
object

Callback to listen for events. List of recording events can be found here. Example event: onStarted.

Returns

Promise<CallRecording>

A promise that resolves to a CallRecording object that you can use to view the current state and results of the recording session.

Example

In this example, we dial a phone number and record the call audio. During the recording, we play a TTS message. Once the TTS message is finished, we hangup the call and print the URL of the recording to console.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();

await call.recordAudio({
beep: true,
format: "mp3",
direction: "both",
initialTimeout: 0,
endSilenceTimeout: 0,
terminators: "#",
stereo: true,
listen: {
onStarted: async (recording) => {
console.log("Recording started");
await call.playTTS({
text: "This is a call recording test.",
});
// Stop the recording after the TTS is played
recording.stop();
},
onFailed: () => {
console.log("Recording failed");
},
onUpdated: (recording) => {
console.log("Recording updated", recording.state);
},
onEnded: (recording) => {
console.log("Recording ended", recording.url, recording.state);
call.hangup();
},
}
}).onStarted();
}
});

sendDigits

sendDigits(digits): Promise<Call>

Play DTMF digits to the other party on the call.

Parameters

digits
stringrequired

The DTMF digits to send to the other party on the call.

Returns

Promise<Call>

A promise that resolves to the current Call object.

Example

In this example, we dial a phone number and send DTMF tones to the other party on the call. After the tones are sent, we hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({
topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
call.answer();

// Send DTMF tones to the Inbound leg of the call
await call.sendDigits("123")
console.log("DTMF tones sent!");
call.hangup();

}
});

tap

tap(params): Promise<CallTap>

Intercept call media and stream it to the specified WebSocket endpoint. Prefer using tapAudio if you only need to tap audio.

caution

This is an experimental method. The destination must be a hosted WebSocket/RTP server, with an address that SignalWire can reach.

A current limitation of this method is that the destination device does not receive any metadata regarding the origin of the stream.

Parameters

params
objectrequired

Object containing the parameters for tapping the call.

params.device
TapDevicerequired

Destination device. Can be either WebSocket or RTP. See TapDevice.

params.audio
objectrequired

An object with the configuration for audio tapping. See audio parameters below.

audio.direction
"listen" | "speak" | "both"required

Direction to tap. Can be "listen" (what the caller hears), "speak" (what the caller says), or "both".

params.listen
object

Callback to listen for events. List of tap events can be found here. Example event: onStarted.

Returns

Promise<CallTap>

A promise that resolves to a CallTap object that you can use to view the current state and results of the tap session.

Example

In this example, we dial a phone number and tap the call audio to a WebSocket endpoint. After the call is tapped, we play a TTS message to the caller, and then stop the tap and hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
await call.answer();

// Start a tap
const callTap = await call.tap({
device: {
type: "ws",
uri: "wss://example.domain.com/websocket_endpoint"
},
audio: {
direction: "both",
},
listen: {
onStarted: () => {
console.log("Tap started");
},
onEnded: () => {
console.log("Tap ended");
},
}
}).onStarted();
await call.playTTS({ text: "We are currently tapping the call audio." });
// Stop the tap
await callTap.stop();
call.hangup();
}
});

tapAudio

tapAudio(params): Promise<CallTap>

Intercept call audio and stream it to the specified WebSocket endpoint.

caution

This is an experimental method. The destination must be a hosted WebSocket/RTP server, with an address that SignalWire can reach.

A current limitation of this method is that the destination device does not receive any metadata regarding the origin of the stream.

Parameters

params
objectrequired

Object containing the parameters for tapping the call audio.

params.device
TapDevicerequired

Destination device. Can be either WebSocket or RTP. See TapDevice.

params.direction
"listen" | "speak" | "both"required

Direction to tap. Can be "listen" (what the caller hears), "speak" (what the caller says), or "both".

params.listen
object

Callback to listen for events. List of tap events can be found here. Example event: onStarted.

Returns

Promise<CallTap>

A promise that resolves to a CallTap object that you can use to view the current state and results of the tap session.

Example

In this example, we dial a phone number and tap the call audio to a WebSocket endpoint. After the call is tapped, we play a TTS message to the caller, and then stop the tap and hangup the call.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
await call.answer();

// Start a tap
const callTap = call.tapAudio({
direction: "both",
device: {
type: "ws",
uri: "wss://example.domain.com/websocket_endpoint"
},
listen: {
onStarted: () => {
console.log("Tap started");
},
onEnded: () => {
console.log("Tap ended");
}
}
}).onStarted();
await call.playTTS({ text: "We are currently tapping the call audio." });
// Stop the tap
await callTap.stop();
call.hangup();
}
});

waitFor

waitFor(params): Promise<boolean>

Returns a promise that is resolved only after the current call is in one of the specified states.

Parameters

params
"ended" | "ending" | ("ended" | "ending")[]required

The call state(s) to wait for.

Returns

Promise<boolean>

A promise that resolves to true if the call is in one of the specified states, or false if the call is ended.

Example

In this example, we dial a phone number and play a TTS message. After the TTS message is finished, we hangup the call and wait for the call to end before printing a message to console.

import { SignalWire } from "@signalwire/realtime-api";

const client = await SignalWire({ project: "ProjectID Here", token: "Token Here" })

const voiceClient = client.voice;

// Listen for incoming calls
await voiceClient.listen({

topics: ["office"],
onCallReceived: async (call) => {
console.log("Call received");
// Answer the call
await call.answer();

// play TTS
await call.playTTS({ text: "Hello World" });

call.hangup();

call.waitFor("ended").then(() => {
console.log("Call ended");
});
}
});

Events

This following examples demonstrate listening to all collect sessions within the application.

tip

A listen can be passed on the call object as a method, or directly inside certain sessions as a parameter. To listen to a specific event within a single session, use listen at the parameter level.

onStateChanged

Call.listen({ onStateChanged: Callback })

Emitted when the state of the call changes. Your event handler will be called with an instance of the CallState object.

Parameters

call
CallStaterequired

A Call object containing the call state. See CallState.

onCollectEnded

Call.listen({ onCollectEnded: Callback })

Emitted when a collect session has ended. Your event handler will be called with an instance of the CallCollect object.

Parameters

collect
CallCollectrequired

A CallCollect object.

onCollectFailed

Call.listen({ onCollectFailed: Callback })

Emitted when a collect session has failed. Your event handler will be called with an instance of the CallCollect object.

Parameters

collect
CallCollectrequired

A CallCollect object.

onCollectInputStarted

Call.listen({ onCollectInputStarted: Callback })

Emitted when a collect session has started. Your event handler will be called with an instance of the CallCollect object.

Parameters

collect
CallCollectrequired

A CallCollect object.

onCollectStarted

Call.listen({ onCollectStarted: Callback })

Emitted when a collect session has started. Your event handler will be called with an instance of the CallCollect object.

Parameters

collect
CallCollectrequired

A CallCollect object.

onCollectUpdated

Call.listen({ onCollectUpdated: Callback })

Emitted when the state of a collect session has changed. Your event handler will be called with an instance of the CallCollect object.

Parameters

collect
CallCollectrequired

A CallCollect object.

onDetectEnded

Call.listen({ onDetectEnded: Callback })

Emitted when a call detection session has ended. Your event handler will be called with an instance of the CallDetect object.

Parameters

detect
CallDetectrequired

A CallDetect object.

onDetectStarted

Call.listen({ onDetectStarted: Callback })

Emitted when a call detection session has started. Your event handler will be called with an instance of the CallDetect object.

Parameters

detect
CallDetectrequired

A CallDetect object.

onDetectUpdated

Call.listen({ onDetectUpdated: Callback })

Emitted when the state of a call detection session has changed. Your event handler will be called with an instance of the CallDetect object.

Parameters

detect
CallDetectrequired

A CallDetect object.

onPlaybackEnded

Call.listen({ onPlaybackEnded: Callback })

Emitted when a playback has ended. Your event handler will be called with an instance of the CallPlayback object.

Parameters

playback
CallPlaybackrequired

A CallPlayback object.

onPlaybackFailed

Call.listen({ onPlaybackFailed: Callback })

Emitted when a playback has failed. Your event handler will be called with an instance of the CallPlayback object.

Parameters

playback
CallPlaybackrequired

A CallPlayback object.

onPlaybackStarted

Call.listen({ onPlaybackStarted: Callback })

Emitted when a playback has started. Your event handler will be called with an instance of the CallPlayback object.

Parameters

playback
CallPlaybackrequired

A CallPlayback object.

onPlaybackUpdated

Call.listen({ onPlaybackUpdated: Callback })

Emitted when the state of a playback has changed. Your event handler will be called with an instance of the CallPlayback object.

Parameters

playback
CallPlaybackrequired

A CallPlayback object.

onPromptEnded

Call.listen({ onPromptEnded: Callback })

Emitted when a prompt has ended. Your event handler will be called with an instance of the CallPrompt object.

Parameters

prompt
CallPromptrequired

A CallPrompt object.

onPromptFailed

Call.listen({ onPromptFailed: Callback })

Emitted when a prompt has failed. Your event handler will be called with an instance of the CallPrompt object.

Parameters

prompt
CallPromptrequired

A CallPrompt object.

onPromptStarted

Call.listen({ onPromptStarted: Callback })

Emitted when a prompt has started. Your event handler will be called with an instance of the CallPrompt object.

Parameters

prompt
CallPromptrequired

A CallPrompt object.

onPromptUpdated

Call.listen({ onPromptUpdated: Callback })

Emitted when the state of a prompt has changed. Your event handler will be called with an instance of the CallPrompt object.

Parameters

prompt
CallPromptrequired

A CallPrompt object.

onRecordingEnded

Call.listen({ onRecordingEnded: Callback })

Emitted when a recording has ended. Your event handler will be called with an instance of the CallRecording object.

Parameters

recording
CallRecordingrequired

A CallRecording object.

onRecordingFailed

Call.listen( { onRecordingFailed: Callback })

Emitted when a recording has failed. Your event handler will be called with an instance of the CallRecording object.

Parameters

recording
CallRecordingrequired

A CallRecording object.

onRecordingStarted

Call.listen({ onRecordingStarted: Callback })

Emitted when a recording has started. Your event handler will be called with an instance of the CallRecording object.

Parameters

recording
CallRecordingrequired

A CallRecording object.

onRecordingUpdated

Call.listen({ onRecordingUpdated: Callback })

Emitted when the state of a recording has changed. Your event handler will be called with an instance of the CallRecording object.

Parameters

recording
CallRecordingrequired

A CallRecording object.

onTapEnded

Call.listen({ onTapEnded: Callback })

Emitted when a tap has ended. Your event handler will be called with an instance of the CallTap object.

Parameters

tap
CallTaprequired

A CallTap object.

onTapStarted

Call.listen({ onTapStarted: Callback })

Emitted when a tap has started. Your event handler will be called with an instance of the CallTap object.

Parameters

tap
CallTaprequired

A CallTap object.