telnyx-voice-streaming-javascript
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinese<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
<!-- Auto-generated from Telnyx OpenAPI specs. Do not edit. -->
Telnyx Voice Streaming - JavaScript
Telnyx 语音流 - JavaScript
Installation
安装
bash
npm install telnyxbash
npm install telnyxSetup
初始化配置
javascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
});All examples below assume is already initialized as shown above.
clientjavascript
import Telnyx from 'telnyx';
const client = new Telnyx({
apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
});以下所有示例均假设已按上述方式完成初始化。
clientError Handling
错误处理
All API calls can fail with network errors, rate limits (429), validation errors (422),
or authentication errors (401). Always handle errors in production code:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('Validation error — check required fields and formats');
}
}
}Common error codes: invalid API key, insufficient permissions,
resource not found, validation error (check field formats),
rate limited (retry with exponential backoff).
401403404422429所有API调用都可能因网络错误、速率限制(429)、校验错误(422)或鉴权错误(401)失败。在生产代码中请务必做好错误处理:
javascript
try {
const result = await client.messages.send({ to: '+13125550001', from: '+13125550002', text: 'Hello' });
} catch (err) {
if (err instanceof Telnyx.APIConnectionError) {
console.error('Network error — check connectivity and retry');
} else if (err instanceof Telnyx.RateLimitError) {
// 429: rate limited — wait and retry with exponential backoff
const retryAfter = err.headers?.['retry-after'] || 1;
await new Promise(r => setTimeout(r, retryAfter * 1000));
} else if (err instanceof Telnyx.APIError) {
console.error(`API error ${err.status}: ${err.message}`);
if (err.status === 422) {
console.error('Validation error — check required fields and formats');
}
}
}常见错误码: API密钥无效, 权限不足, 资源未找到, 校验错误(请检查字段格式), 触发速率限制(请使用指数退避策略重试)。
401403404422429Forking start
启动媒体分流
Call forking allows you to stream the media from a call to a specific target in realtime. This stream can be used to enable realtime audio analysis to support a
variety of use cases, including fraud detection, or the creation of AI-generated audio responses. Requests must specify either the attribute or the and attributes.
targetrxtxPOST /calls/{call_control_id}/actions/fork_startOptional: (string), (string), (string), (enum: decrypted), (string)
client_statecommand_idrxstream_typetxjavascript
const response = await client.calls.actions.startForking('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result通话分流功能允许你将通话中的媒体实时流转到指定目标,该流可用于实现实时音频分析,支撑多种使用场景,包括欺诈检测、生成AI音频响应等。请求必须指定属性,或和属性。
targetrxtxPOST /calls/{call_control_id}/actions/fork_start可选参数:(字符串)、(字符串)、(字符串)、(枚举值:decrypted)、(字符串)
client_statecommand_idrxstream_typetxjavascript
const response = await client.calls.actions.startForking('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultForking stop
停止媒体分流
Stop forking a call. Expected Webhooks:
call.fork.stopped
POST /calls/{call_control_id}/actions/fork_stopOptional: (string), (string), (enum: raw, decrypted)
client_statecommand_idstream_typejavascript
const response = await client.calls.actions.stopForking('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result停止通话分流。预期触发的Webhook:
call.fork.stopped
POST /calls/{call_control_id}/actions/fork_stop可选参数:(字符串)、(字符串)、(枚举值:raw, decrypted)
client_statecommand_idstream_typejavascript
const response = await client.calls.actions.stopForking('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultStreaming start
启动媒体流
Start streaming the media from a call to a specific WebSocket address or Dialogflow connection in near-realtime. Audio will be delivered as base64-encoded RTP payload (raw audio), wrapped in JSON payloads. Please find more details about media streaming messages specification under the link.
POST /calls/{call_control_id}/actions/streaming_startOptional: (string), (string), (array[object]), (object), (boolean), (string), (enum: PCMU, PCMA, G722, OPUS, AMR-WB, L16), (enum: mp3, rtp), (enum: 8000, 16000, 22050, 24000, 48000), (enum: both, self, opposite), (enum: PCMU, PCMA, G722, OPUS, AMR-WB, L16, default), (enum: inbound_track, outbound_track, both_tracks), (string)
client_statecommand_idcustom_parametersdialogflow_configenable_dialogflowstream_auth_tokenstream_bidirectional_codecstream_bidirectional_modestream_bidirectional_sampling_ratestream_bidirectional_target_legsstream_codecstream_trackstream_urljavascript
const response = await client.calls.actions.startStreaming('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result近乎实时地将通话媒体流转到指定WebSocket地址或Dialogflow连接。音频将以base64编码的RTP payload(原始音频)形式封装在JSON payload中传输。你可以通过链接查看媒体流消息规范的更多详情。
POST /calls/{call_control_id}/actions/streaming_start可选参数:(字符串)、(字符串)、(数组[对象])、(对象)、(布尔值)、(字符串)、(枚举值:PCMU, PCMA, G722, OPUS, AMR-WB, L16)、(枚举值:mp3, rtp)、(枚举值:8000, 16000, 22050, 24000, 48000)、(枚举值:both, self, opposite)、(枚举值:PCMU, PCMA, G722, OPUS, AMR-WB, L16, default)、(枚举值:inbound_track, outbound_track, both_tracks)、(字符串)
client_statecommand_idcustom_parametersdialogflow_configenable_dialogflowstream_auth_tokenstream_bidirectional_codecstream_bidirectional_modestream_bidirectional_sampling_ratestream_bidirectional_target_legsstream_codecstream_trackstream_urljavascript
const response = await client.calls.actions.startStreaming('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultStreaming stop
停止媒体流
Stop streaming a call to a WebSocket. Expected Webhooks:
streaming.stopped
POST /calls/{call_control_id}/actions/streaming_stopOptional: (string), (string), (uuid)
client_statecommand_idstream_idjavascript
const response = await client.calls.actions.stopStreaming('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result停止将通话流转到WebSocket。预期触发的Webhook:
streaming.stopped
POST /calls/{call_control_id}/actions/streaming_stop可选参数:(字符串)、(字符串)、(uuid)
client_statecommand_idstream_idjavascript
const response = await client.calls.actions.stopStreaming('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultTranscription start
启动实时转写
Start real-time transcription. Transcription will stop on call hang-up, or can be initiated via the Transcription stop command. Expected Webhooks:
call.transcription
POST /calls/{call_control_id}/actions/transcription_startOptional: (string), (string), (enum: Google, Telnyx, Deepgram, Azure, A, B), (object), (string)
client_statecommand_idtranscription_enginetranscription_engine_configtranscription_tracksjavascript
const response = await client.calls.actions.startTranscription('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result启动实时语音转写。转写将在通话挂断时自动停止,也可通过转写停止命令手动终止。预期触发的Webhook:
call.transcription
POST /calls/{call_control_id}/actions/transcription_start可选参数:(字符串)、(字符串)、(枚举值:Google, Telnyx, Deepgram, Azure, A, B)、(对象)、(字符串)
client_statecommand_idtranscription_enginetranscription_engine_configtranscription_tracksjavascript
const response = await client.calls.actions.startTranscription('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultTranscription stop
停止实时转写
Stop real-time transcription.
POST /calls/{call_control_id}/actions/transcription_stopOptional: (string), (string)
client_statecommand_idjavascript
const response = await client.calls.actions.stopTranscription('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);Returns: (string)
result停止实时语音转写。
POST /calls/{call_control_id}/actions/transcription_stop可选参数:(字符串)、(字符串)
client_statecommand_idjavascript
const response = await client.calls.actions.stopTranscription('v3:550e8400-e29b-41d4-a716-446655440000_gRU1OGRkYQ');
console.log(response.data);返回值:(字符串)
resultWebhooks
Webhooks
Webhook Verification
Webhook 验签
Telnyx signs webhooks with Ed25519. Each request includes
and headers. Always verify signatures in production:
telnyx-signature-ed25519telnyx-timestampjavascript
// In your webhook handler (e.g., Express — use raw body, not parsed JSON):
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
try {
const event = await client.webhooks.unwrap(req.body.toString(), {
headers: req.headers,
});
// Signature valid — event is the parsed webhook payload
console.log('Received event:', event.data.event_type);
res.status(200).send('OK');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Invalid signature');
}
});The following webhook events are sent to your configured webhook URL.
All webhooks include and headers for Ed25519 signature verification. Use to verify.
telnyx-timestamptelnyx-signature-ed25519client.webhooks.unwrap()| Event | Description |
|---|---|
| Call Fork Started |
| Call Fork Stopped |
| Call Streaming Failed |
| Call Streaming Started |
| Call Streaming Stopped |
| Transcription |
Telnyx使用Ed25519对Webhook进行签名,每个请求都包含和请求头。生产环境中请务必验证签名:
telnyx-signature-ed25519telnyx-timestampjavascript
// In your webhook handler (e.g., Express — use raw body, not parsed JSON):
app.post('/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
try {
const event = await client.webhooks.unwrap(req.body.toString(), {
headers: req.headers,
});
// Signature valid — event is the parsed webhook payload
console.log('Received event:', event.data.event_type);
res.status(200).send('OK');
} catch (err) {
console.error('Webhook verification failed:', err.message);
res.status(400).send('Invalid signature');
}
});以下Webhook事件会发送到你配置的Webhook地址。所有Webhook都包含和头,用于Ed25519签名验证,可使用完成验签。
telnyx-timestamptelnyx-signature-ed25519client.webhooks.unwrap()| 事件 | 描述 |
|---|---|
| 通话分流已启动 |
| 通话分流已停止 |
| 通话流转失败 |
| 通话流转已启动 |
| 通话流转已停止 |
| 转写结果 |
Webhook payload fields
Webhook 载荷字段
callForkStarted| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.fork.started | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | Unique ID for controlling the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| enum: decrypted | Type of media streamed. |
callForkStopped| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.fork.stopped | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | Unique ID for controlling the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| enum: decrypted | Type of media streamed. |
callStreamingFailed| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the resource. |
| enum: streaming.failed | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | A short description explaning why the media streaming failed. |
| uuid | Identifies the streaming. |
| enum: websocket, dialogflow | The type of stream connection the stream is performing. |
callStreamingStarted| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: streaming.started | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Destination WebSocket address where the stream is going to be delivered. |
callStreamingStopped| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: streaming.stopped | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Call ID used to issue commands via Call Control API. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | State received from a command. |
| string | Destination WebSocket address where the stream is going to be delivered. |
transcription| Field | Type | Description |
|---|---|---|
| enum: event | Identifies the type of the resource. |
| enum: call.transcription | The type of event being delivered. |
| uuid | Identifies the type of resource. |
| date-time | ISO 8601 datetime of when the event occurred. |
| string | Unique identifier and token for controlling the call. |
| string | ID that is unique to the call and can be used to correlate webhook events. |
| string | ID that is unique to the call session and can be used to correlate webhook events. |
| string | Use this field to add state to every subsequent webhook. |
| string | Call Control App ID (formerly Telnyx connection ID) used in the call. |
callForkStarted| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: call.fork.started | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |
| 字符串 | 控制通话的唯一ID |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从命令中传递的状态值 |
| 枚举值: decrypted | 流转的媒体类型 |
callForkStopped| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: call.fork.stopped | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |
| 字符串 | 控制通话的唯一ID |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从命令中传递的状态值 |
| 枚举值: decrypted | 流转的媒体类型 |
callStreamingFailed| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: streaming.failed | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过Call Control API下发命令的通话ID |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从命令中传递的状态值 |
| 字符串 | 媒体流转失败的简短说明 |
| uuid | 媒体流唯一标识 |
| 枚举值: websocket, dialogflow | 流连接的类型 |
callStreamingStarted| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: streaming.started | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过Call Control API下发命令的通话ID |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从命令中传递的状态值 |
| 字符串 | 媒体流投递的目标WebSocket地址 |
callStreamingStopped| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: streaming.stopped | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 用于通过Call Control API下发命令的通话ID |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 从命令中传递的状态值 |
| 字符串 | 媒体流投递的目标WebSocket地址 |
transcription| 字段 | 类型 | 描述 |
|---|---|---|
| 枚举值: event | 标识资源类型 |
| 枚举值: call.transcription | 触发的事件类型 |
| uuid | 资源ID |
| date-time | 事件发生的ISO 8601格式时间戳 |
| 字符串 | 控制通话的唯一标识和令牌 |
| 字符串 | 通话单路唯一ID,可用于关联Webhook事件 |
| 字符串 | 通话会话唯一ID,可用于关联Webhook事件 |
| 字符串 | 可通过该字段为后续所有Webhook附加状态信息 |
| 字符串 | 通话使用的Call Control App ID(原Telnyx连接ID) |