0

Speak text

by
Published Apr 8, 2025

Convert text to speech and play it back on the call. If multiple speak text commands are issued consecutively, the audio files will be placed in a queue awaiting playback. **Expected Webhooks (see [callback schema](https://developers.telnyx.com/api/call-control/speak-call#callbacks) below):** - `call.speak.started` - `call.speak.ended`

Script telnyx Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Telnyx = {
3
	apiKey: string
4
}
5
/**
6
 * Speak text
7
 * Convert text to speech and play it back on the call. If multiple speak text commands are issued consecutively, the audio files will be placed in a queue awaiting playback.
8

9
**Expected Webhooks (see [callback schema](https://developers.telnyx.com/api/call-control/speak-call#callbacks) below):**
10

11
- `call.speak.started`
12
- `call.speak.ended`
13

14
 */
15
export async function main(
16
	auth: Telnyx,
17
	call_control_id: string,
18
	body: {
19
		payload: string
20
		payload_type?: 'text' | 'ssml'
21
		service_level?: 'basic' | 'premium'
22
		stop?: string
23
		voice: string
24
		voice_settings?: { api_key_ref?: string }
25
		language?:
26
			| 'arb'
27
			| 'cmn-CN'
28
			| 'cy-GB'
29
			| 'da-DK'
30
			| 'de-DE'
31
			| 'en-AU'
32
			| 'en-GB'
33
			| 'en-GB-WLS'
34
			| 'en-IN'
35
			| 'en-US'
36
			| 'es-ES'
37
			| 'es-MX'
38
			| 'es-US'
39
			| 'fr-CA'
40
			| 'fr-FR'
41
			| 'hi-IN'
42
			| 'is-IS'
43
			| 'it-IT'
44
			| 'ja-JP'
45
			| 'ko-KR'
46
			| 'nb-NO'
47
			| 'nl-NL'
48
			| 'pl-PL'
49
			| 'pt-BR'
50
			| 'pt-PT'
51
			| 'ro-RO'
52
			| 'ru-RU'
53
			| 'sv-SE'
54
			| 'tr-TR'
55
		client_state?: string
56
		command_id?: string
57
	}
58
) {
59
	const url = new URL(`https://api.telnyx.com/v2/calls/${call_control_id}/actions/speak`)
60

61
	const response = await fetch(url, {
62
		method: 'POST',
63
		headers: {
64
			'Content-Type': 'application/json',
65
			Authorization: 'Bearer ' + auth.apiKey
66
		},
67
		body: JSON.stringify(body)
68
	})
69
	if (!response.ok) {
70
		const text = await response.text()
71
		throw new Error(`${response.status} ${text}`)
72
	}
73
	return await response.json()
74
}
75