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​

• device: any


direction​

• direction: "inbound" | "outbound"

Whether you are making or receiving the call.


from​

• from: string

The phone number that the call is coming from.


headers​

• Optional headers: SipHeader[]


id​

• Readonly id: string

Unique ID for this voice call.


state​

• state: created | ringing | answered | ending | ended

The current state of the call.


to​

• to: string

The phone number you are attempting to call.


type​

• 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​

NameTypeDescription
paramsObject-
params.continuous?booleanDetect utterances and digits until stopped. Defaults to false.
params.digits?CollectDigitsConfigConfiguration for collecting digits. You must either set this, or speech.
params.speech?CollectSpeechConfigConfiguration for collecting speech. You must either set this, or digits.
params.initialTimeout?numberNumber of seconds to wait for initial input before giving up. Default is 4 seconds. Will be used only when startInputTimers is true or when the timer is started manually via the startInputTimers method.
params.partialResults?booleanIf true, partial result events are fired. Default is false.
params.sendStartOfInput?booleanIf true, the startOfInput event is fired when input is detected. Default is false.
params.startInputTimers?booleanIf true, the initialTimeout timer is started. Default is false.
params.listen?CallbackCallback 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​

NameTypeDescription
paramsObject-
params.devicesVoiceDeviceBuilderPass only the Dialer specifying the devices to call.
params.ringback?VoicePlaylistRingback audio to play to the first call leg. You can play audio, TTS, silence or ringtone.
params.maxPricePerMinute?numberThe 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.

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​

NameTypeDescription
paramsObject-
params.callStateEventsstring[]An optional array of event names to be notified about. Allowed values are created, ringing, answered, and ended. Default is ended.
params.callStateUrlstringOptional webhook URL to which SignalWire will send call status change notifications. See the payload specifications under CallState.
params.fromstringThe party the call is coming from. Must be a SignalWire number or SIP endpoint that you own.
params.maxPricePerMinute?numberThe 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?VoicePlaylistRingback audio to play to call leg. You can play audio, TTS, silence or ringtone.
params.timeout?numberThe time, in seconds, the call will ring before it is considered unanswered.
params.tostringThe party you are attempting to call.

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​

NameTypeDescription
paramsObject-
params.callStateEventsstring[]An optional array of event names to be notified about. Allowed values are created, ringing, answered, and ended. Default is ended.
params.callStateUrlstringOptional webhook URL to which SignalWire will send call status change notifications. See the payload specifications under CallState.
params.codecs?SipCodec[]Optional array of desired codecs in order of preference. Supported values are PCMU, PCMA, OPUS, G729, G722, VP8, H264. Default is parent leg codec(s).
params.fromstringThe party the call is coming from. Must be a SignalWire number or SIP endpoint that you own.
params.headers?SipHeader[]Array of SipHeader objects. Must be X- headers only, see example below.
params.maxPricePerMinute?numberThe 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?VoicePlaylistRingback audio to play to call leg. You can play audio, TTS, silence or ringtone.
params.timeout?numberThe time, in seconds, the call will ring before it is considered unanswered.
params.tostringThe party you are attempting to call.
params.webrtcMedia?booleanIf true, WebRTC media is negotiated. Default is parent leg setting.
params.sessionTimeout?numberNon-negative value, in seconds, to use for the SIP Session-Expires header. If 0 or unset, SignalWire will pick the default (typically 600).

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​

NameTypeDescription
paramsobject-
params.type"fax" | "machine" | "digit" | "beep"

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​

NameTypeDescription
params?Object-
params.endSilenceTimeout?numberNumber of seconds to wait for voice to finish. Defaults to 1.0.
params.initialTimeout?numberNumber of seconds to wait for initial voice before giving up. Defaults to 4.5.
params.machineReadyTimeout?numberNumber of seconds to wait for voice to finish before firing the READY event. Default is the value of end_silence_timeout.
params.machineVoiceThreshold?numberHow many seconds of voice to decide it is a machine. Defaults to 1.25.
params.machineWordsThreshold?numberHow many words to count to decide it is a machine. Defaults to 6.
params.timeout?numberNumber of seconds to run the detector for. Defaults to 30.0.
params.waitForBeep?booleanWhether to wait until the device is ready for voicemail delivery. Defaults to false.
params.detectInterruptions?booleanIf set to true, a NOT_READY event is fired if speech is detected after the READY event. This allows application to restart message delivery to answering machine. Defaults to false.
params.listen?ObjectCallback 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​

NameTypeDescription
params?Object-
params.digits?stringThe digits to detect. Defaults to 0123456789#\*.
params.timeout?numberNumber of seconds to run the detector for. Defaults to 30.0.
params.waitForBeep?booleanWhether to wait until the device is ready for voicemail delivery. Defaults to false.
params.listen?ObjectCallback 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​

NameTypeDescription
params?Object-
params.timeout?numberNumber of seconds to run the detector for. Defaults to 30.0.
params.tone?"CED" | "CNG"The fax tone to detect: CED or CNG. Defaults to CED.
params.waitForBeep?booleanWhether to wait until the device is ready for voicemail delivery. Defaults to false.
params.listen?ObjectCallback 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​

NameTypeDescription
reason?"error" | "hangup" | "cancel" | "busy" | "noAnswer" | "decline"Optional 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>

Listen for events on the call.

Parameters​

NameTypeDescription
paramsObject-
params.topicsstring[]An array of topics to listen for.
params.EVENTCallbackThe event to listen to. List of events can be found here.
Example event: onStateChanged

Returns​

Promise<Call Events>

An event that resolves to a Call Events object that you can use to view the current state or results of the event.

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​

NameTypeDescription
paramsObject-
params.playlistVoicePlaylistA media playlist.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.urlstringHTTP(s) URL to an audio resource to play.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.duration?numberDuration of ringtone to play. Defaults to 1 ringtone iteration.
params.nameRingtoneNameThe name of the ringtone.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.durationnumberSeconds of silence to play.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.gender?"male" | "female"Gender of the voice. Defaults to female.
params.language?stringLanguage of the text in ISO 639-1 (language name) + ISO 3166 (country code). Defaults to en-US.
Supported languages can be found here.
params.textstringText 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.voice?stringVoice to use (takes precedence on gender).
Supported voices can be found here.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.playlistVoicePlaylistA media playlist to play.
params.digits?CollectDigitsConfigConfiguration for collecting digits. You must either set this, or speech.
params.speech?CollectSpeechConfigConfiguration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration.
params.initialTimeout?numberInitial timeout in seconds. Default is 4 seconds.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.digits?CollectDigitsConfigConfiguration for collecting digits. You must either set this, or speech.
params.speech?CollectSpeechConfigConfiguration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration.
params.initialTimeout?numberInitial timeout in seconds. Default is 4 seconds.
params.urlstringHTTP(s) URL to an audio resource to play.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.nameRingtoneNameThe name of the ringtone.
params.digits?CollectDigitsConfigConfiguration for collecting digits. You must either set this, or speech.
params.speech?CollectSpeechConfigConfiguration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration.
params.duration?numberDuration of ringtone to play. Defaults to 1 ringtone iteration.
params.initialTimeout?numberInitial timeout in seconds. Default is 4 seconds.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.textstringText to play. SSML (Speech Synthesis Markup Language) may be entered as a string wrapped in <speak> tags.
See our supported voices and languages documentation for usage and supported tags.
params.digits?CollectDigitsConfigConfiguration for collecting digits. You must either set this, or speech.
params.speech?CollectSpeechConfigConfiguration for collecting speech. You must either set this, or digits. Pass an empty object to use the default configuration.
params.gender?"male" | "female"Gender of the voice (male or female). Defaults to female.
params.initialTimeout?numberInitial timeout in seconds. Default is 4 seconds.
params.language?stringLanguage of the text in ISO 639-1 (language name) + ISO 3166 (country code). Defaults to en-US.
Supported languages can be found here.
params.volume?numberVolume value between -40dB and +40dB where 0 is unchanged. Default is 0.
params.voice?stringVoice to use (takes precedence on gender).
Supported voices can be found here.
params.listen?ObjectCallback 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​

NameTypeDescription
paramsObject-
params.audioObjectSee the parameters for recordAudio.
params.listen?ObjectCallback 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​

NameTypeDescription
params?Object-
params.beep?booleanWhether to play a beep. Default is false.
params.direction?"listen" | "speak" | "both"Direction to record. Can be listen (what the caller hears), speak (what the caller says), or both. Default is speak.
params.endSilenceTimeout?numberHow long to wait (in seconds) until the caller has stopped speaking. Disable by passing 0. Default is 1.0.
params.format?"mp3" | "wav"Format of the recording. Default is mp3.
params.initialTimeout?numberHow long to wait (in seconds) until something is heard in the recording. Disable by passing 0. Default is 5.0.
params.inputSensitivity?numberControls how sensitive the voice activity detector is to background noise, where 0 is least sensitive and 100 is most sensitive. Default is 44.0.
params.stereo?booleanWhether to record in stereo mode. Default is false.
params.terminators?stringDTMF digits that, when dialed, will end the recording. Default is #\*.
params.listen?ObjectCallback 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​

NameType
digitsstring

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​

NameTypeDescription
paramsObject-
params.deviceTapDeviceDestination device. Can be either WebSocket or RTP.
params.audioObjectAn object with the configuration for audio tapping. See "audio parameters" below.
params.listen?ObjectCallback to listen for events.
List of tap events can be found here.
Example event: onStarted

Audio parameters

NameTypeDescription
audioObject-
audio.direction"listen" | "speak" | "both"Direction to tap. Can be "listen" (what the caller hears), "speak" (what the caller says), or "both".

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​

NameTypeDescription
paramsObject-
params.deviceTapDeviceDestination device. Can be either WebSocket or RTP.
params.direction"listen" | "speak" | "both"Direction to tap. Can be "listen" (what the caller hears), "speak" (what the caller says), or "both".
params.listen?ObjectCallback 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​

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

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​

NameTypeDescription
callCallStateA Call object containing the call state.

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​

NameTypeDescription
collectCallCollectA 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​

NameTypeDescription
collectCallCollectA 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​

NameTypeDescription
collectCallCollectA 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​

NameTypeDescription
collectCallCollectA 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​

NameTypeDescription
collectCallCollectA 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​

NameTypeDescription
detectCallDetectA 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​

NameTypeDescription
detectCallDetectA 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​

NameTypeDescription
detectCallDetectA 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​

NameTypeDescription
playbackCallPlaybackA 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​

NameTypeDescription
playbackCallPlaybackA 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​

NameTypeDescription
playbackCallPlaybackA 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​

NameTypeDescription
promptCallPromptA 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​

NameTypeDescription
promptCallPromptA 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​

NameTypeDescription
promptCallPromptA 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​

NameTypeDescription
promptCallPromptA 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​

NameTypeDescription
recordingCallRecordingA 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​

NameTypeDescription
recordingCallRecordingA 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​

NameTypeDescription
recordingCallRecordingA 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​

NameTypeDescription
recordingCallRecordingA 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​

NameTypeDescription
tapCallTapA 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​

NameTypeDescription
tapCallTapA CallTap object.