Real-time Speech Synthesis WebSocket API Reference

Updated at:
[ {"id":"node1","type":"process","x":100,"y":50,"label":"Client"}, {"id":"node2","type":"process","x":300,"y":50,"label":"WebSocket gateway"}, {"id":"node3","type":"process","x":500,"y":50,"label":"Speech synthesis service"}, {"id":"node4","type":"process","x":100,"y":150,"label":"Client connects to WebSocket gateway."}, {"id":"node5","type":"process","x":300,"y":150,"label":"Gateway connects to synthesis service."}, {"id":"node6","type":"process","x":100,"y":250,"label":"Client sends synthesis requests."}, {"id":"node7","type":"process","x":300,"y":250,"label":"Gateway forwards requests."}, {"id":"node8","type":"process","x":500,"y":250,"label":"Service processes requests, returns speech data."}, {"id":"node9","type":"process","x":100,"y":350,"label":"Client receives and plays speech."}, {"id":"node10","type":"process","x":300,"y":350,"label":"Gateway forwards speech data."}, {"id":"node11","type":"process","x":100,"y":450,"label":"Client sends completion message."}, {"id":"node12","type":"process","x":300,"y":450,"label":"Gateway forwards completion message."}, {"id":"node13","type":"process","x":500,"y":450,"label":"Service receives message, disconnects from gateway."}, {"id":"node14","type":"process","x":300,"y":550,"label":"Gateway disconnects from client."}, {"id":"edge1","source":"node1","target":"node4","label":"","type":"link"}, {"id":"edge2","source":"node2","target":"node5","label":"","type":"link"}, {"id":"edge3","source":"node4","target":"node5","label":"","type":"link"}, {"id":"edge4","source":"node5","target":"node6","label":"","type":"link"}, {"id":"edge5","source":"node6","target":"node7","label":"","type":"link"}, {"id":"edge6","source":"node7","target":"node8","label":"","type":"link"}, {"id":"edge7","source":"node8","target":"node10","label":"","type":"link"}, {"id":"edge8","source":"node10","target":"node9","label":"","type":"link"}, {"id":"edge9","source":"node9","target":"node11","label":"","type":"link"}, {"id":"edge10","source":"node11","target":"node12","label":"","type":"link"}, {"id":"edge11","source":"node12","target":"node13","label":"","type":"link"}, {"id":"edge12","source":"node13","target":"node14","label":"","type":"link"} ]

The real-time speech synthesis API provides streaming synthesis over a single WebSocket connection, allowing you to send text and receive audio concurrently. It is ideal for converting streaming output from large language models to speech, real-time conversations, and streaming or long-form announcements. This topic describes the interaction flow, API endpoint, and request headers for accessing the Voice Studio real-time speech synthesis service via WebSocket.

Endpoint

The WebSocket URL is:

wss://convai-platform.aliyuncs.com/api-ws/v1/inference

Authentication

Client type

Authentication method

Example

Server-side (Java / Python / Node / Go, etc.)

Handshake request header Authorization: Bearer <api_key>

Authorization: Bearer sk-9f2ac...d41b

Browser

URL query parameter ?token=<api_key>

wss://.../api-ws/v1/inference?token=sk-9f2ac...d41b

  • API Keys are issued by Voice Studio and consist of the prefix sk- followed by 32 hexadecimal characters. For instructions on obtaining a key, see API Key. Keys from Model Studio will fail authentication, resulting in an HTTP 401 response.

  • The WebSocket object in a browser does not allow custom handshake request headers. Therefore, you must pass credentials and all toggles as URL query parameters. For browser-based applications, your backend should issue a temporary token valid for up to 2 hours. Do not expose a long-lived API Key to the client.

  • If authentication fails, the server returns an HTTP 401 error during the handshake phase (in a browser, this may appear only as close code 1006). Credential issues after the connection is upgraded result in close code 4401.

Request headers

All handshake parameters are session-level and cannot be changed after the connection is established. To use different values, open a new connection.

Request header

Required

Value

Description

Authorization

Required for server-side

Bearer <api_key>

API Key issued by Voice Studio.

X-TTS-TN

No

enable

Enables text normalization (TN). The value must exactly match enable (case-sensitive). Values such as Enable, true, or 1 are ignored.

URL query parameters

Parameter

Required

Default

Description

token

Required for browsers

-

The authentication credential for browser-based connections. For server-side connections, use the Authorization request header instead.

tn

No

Disabled

Set to enable to enable text normalization. This is equivalent to X-TTS-TN: enable. The service enables text normalization if either this parameter or the header is specified.

voice

No

-

The session-level default voice, specified as a platform voice ID. This voice is used as a fallback if run-task does not include a parameters.voice value.

requestId

No

-

A custom tracking ID of up to 64 characters, used for log troubleshooting. We strongly recommend including this parameter. If a handshake fails, a browser might only receive the close code 1006, which makes this ID the only way to trace the request for debugging.

Handshake example (server-side, TN enabled)

GET /api-ws/v1/inference?requestId=svc-20260903-0001 HTTP/1.1
Host: convai-platform.aliyuncs.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: dGhl************==
Authorization: Bearer sk-9f2ac...d41b
X-TTS-TN: enable

Handshake example (browser)

wss://convai-platform.aliyuncs.com/api-ws/v1/inference
  ?token=sk-9f2ac...d41b
  &tn=enable
  &voice=9f2a1c4e-7b30-4d51-8a6c-2e5f1b8d0a56
  &requestId=web-20260903-7f3a91

Interaction flow

  1. Establish connection: Initiate the WebSocket handshake with the authentication information as described above and receive a 101 Switching Protocols response. In the default strict mode, the service sends no additional downstream frames.

  2. Send run-task: Specify the voice and audio parameters to start a synthesis task. You must generate a task_id (for example, a UUID) and use the same ID for all frames within that task.

  3. Wait for task-started: Send text only after receiving this event. Sending text before this event results in an InvalidParameter error.

  4. Send continue-task: Send text in incremental chunks. You can send this message multiple times. The interval between two consecutive messages must be less than 20 seconds.

  5. Receive result-generated: The service sends metadata for each sentence. The event's type arrives in the following sequence: sentence-begin → sentence-synthesis (can occur multiple times) → sentence-end.

  6. Receive binary audio frames: Each result-generated event with type=sentence-synthesis is immediately followed by a binary audio frame. Append these frames in the order you receive them to play the audio or write to a file. No reordering is necessary.

  7. (Optional) Send flush: The service holds a sentence fragment in a buffer and does not synthesize it immediately. To force the synthesis of the buffered fragment, send a flush message.

  8. Send finish-task: This step is mandatory. The service flushes the buffer and synthesizes all remaining content, including any trailing sentence fragments.

  9. Continue receiving until task-finished: Audio frames can still arrive after you send the finish-task message. Closing the connection prematurely results in lost trailing audio. The task-finished event includes the number of billable characters and the link ID for the task.

  10. Reuse or close the connection: After a task is complete, you can either initiate a new run-task with a new task_id on the same connection or close the connection.

State constraints

Constraint

Consequence

You must send a run-task message and wait for the task-started event before sending text.

InvalidParameter

The task_id must be identical for all frames within the same task.

InvalidParameter: task_id mismatch

Only one task can run on a connection at a time.

InvalidParameter: another task is running

The finish-task message is required.

Text remaining in the buffer is not synthesized, resulting in incomplete audio.

After sending a finish-task message, continue to receive data until the task-finished event arrives.

Closing the connection prematurely results in lost trailing audio.

Upstream frames must be TEXT frames.

Sending a binary frame returns a task-failed(InvalidParameter) error, but the connection remains open.

Client events (uplink)

All uplink events must be TEXT frames and use the following envelope structure:

{
  "header": {
    "action": "<event name>",
    "task_id": "<the UUID that you generate>",
    "streaming": "duplex"
  },
  "payload": { }
}

header field

Type

Required

Value

Description

action

String

Yes

run-task / continue-task / finish-task

Any other value returns an InvalidParameter: unknown action: xxx error.

task_id

String

Yes

UUID string

A UUID that you generate. It must be the same for all frames within the same task.

streaming

String

Recommended

Fixed duplex

If this parameter is specified, its value must be duplex. Although the parameter is optional, we recommend that you always specify it to ensure compatibility with future versions.

Unknown fields are ignored and do not cause errors. This ensures forward compatibility.

1. run-task — Start a task

When to send: Send this as the first frame after establishing the connection.

Response events: Returns task-started on success and task-failed on failure.

Quantity limit: A connection allows only one task at a time. After the previous task is finished, you can send another task with a new task_id.

Top-level payload fields

Parameter

Type

Required

Description

model

String

No

Deprecated. Retained only for compatibility with the request body structure of the Model Studio SDK. The synthesis model is determined by the platform voice corresponding to parameters.voice. Any value passed is ignored and does not cause an error.

parameters

Object

Yes

Synthesis parameters. See the following two tables for details.

input

Object

Yes

In the run-task stage, a fixed {} is passed, and the text is sent by using continue-task.

parameters — Audio parameters

Parameter

Type

Required

Default

Range

Description

voice

String

Yes (can fall back to the handshake voice)

handshake voice

-

The platform voice ID must be in UUID format. The {model}:{voice} format or bare voice names are not accepted.

format

String

No

mp3

mp3 / pcm / wav / opus

The audio encoding format.

sample_rate

Integer

No

22050 (or 24000 if format=opus)

8000 / 16000 / 22050 / 24000 / 44100 / 48000

The sample rate in Hz. When format is opus, only the following values are supported: 8000, 16000, 24000, and 48000.

volume

Integer

No

50

[0, 100]

The audio volume.

rate

Float

No

1.0

[0.5, 2.0]

The speech rate multiplier.

pitch

Float

No

1.0

[0.5, 2.0]

The pitch multiplier.

bit_rate

Integer

No

Engine default (approx. 32)

[6, 510]

Bit rate (kbps). Only format=mp3 or opus are supported. For other formats, an InvalidParameter error is returned.

background_sound

String

No

No background sound

office / office_mix

The type of background sound. This parameter can be used only when format=pcm or format=wav. If this parameter is not specified, no background sound is mixed in. For more information, see Background sound.

background_snr

Float

No

Randomly adjusted by the service

[-5, 40]

The signal-to-noise ratio (SNR) in dB. This parameter supports decimal values. A higher value indicates that the background sound is quieter. If you specify a value, the SNR is fixed to that value. Otherwise, the service automatically and randomly adjusts the SNR. This parameter takes effect only when the background_sound parameter is specified.

parameters — Feature parameters

Parameter

Type

Required

Default

Value / Constraint

Description

enable_ssml

Boolean

No

false

Mutually exclusive with vocabulary_id

Enables SSML tag parsing. If enabled, only one continue-task message is allowed for the entire task.

word_timestamp_enabled

Boolean

No

false

Mutually exclusive with flush

Enables word-level timestamps. If enabled, the sentence-end event will include a words[] array.

language_hints

Array[String]

No

-

For example, ["zh"]

A hint for the target language. The current engine only considers the first element in the array.

seed

Integer

No

-

[0, 65535]

A random seed. Using the same seed and text produces reproducible synthesis results.

instruction

String

No

-

≤ 2000 characters

Instruction-based control for dialect, emotion, or role. Not supported by all models.

vocabulary_id

String

No

-

UUID

References a vocabulary that is enabled for the authenticated identity.

hot_fix

Object

No

-

For example, {"replace":[{"source word":"replacement text"}],"pronunciation":["source":"replacement pronunciation"]}

Hot fix rules. The replace rules are executed by the platform as temporary rules for the task and can override rules with the same source word in a vocabulary.

enable_markdown_filter

Boolean

No

false

-

Filters Markdown syntax before synthesis. Not supported by all models.

enable_aigc_tag

Boolean

No

false

-

Embeds an AIGC implicit identifier in the audio. Use this field with aigc_propagator and aigc_propagate_id.

aigc_propagator

String

No

-

-

The AIGC identifier propagator.

aigc_propagate_id

String

No

-

-

The AIGC identifier propagation ID.

pronunciation temporary rules ≤ 128; UTF-8 size of canonical compact JSON ≤ 16 KiB.

The number of replace temporary rules is ≤ 128, and the UTF-8 size of canonical compact JSON is ≤ 16 KiB.

You cannot use vocabulary_id when enable_ssml is true.

Example

{
  "header": {
    "action": "run-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": {
    "parameters": {
      "voice": "9f2a1c4e-7b30-4d51-8a6c-2e5f1b8d0a37",
      "format": "mp3",
      "vocabulary_id": "123e4567-e89b-42d3-a456-426614174000",
      "hot_fix": {
        "replace": [
          {"ConvAI": "ConvAI Intelligence"},
          {"VIP": "VIP guest"}
        ],
        "pronunciation": [
          {"行": "hang2"},
          {"天气": "tian1 qi4"}
        ]
      },
      "sample_rate": 22050,
      "volume": 50,
      "rate": 1.0,
      "pitch": 1.0,
      "word_timestamp_enabled": true,
      "language_hints": ["zh"],
      "seed": 1024
    },
    "input": {}
  }
}

2. continue-task — Send text incrementally

When to send: After task-started is received, it can be sent multiple times.

Response event: result-generated + BINARY audio frames (when a complete sentence is formed). If the text does not form a complete sentence, no downstream events are generated.

Quantity Limits: Up to 20,000 characters per request (based on the source text), and a cumulative limit of 200,000 characters per task. When enable_ssml=true, only one request is allowed for the entire task.

payload field

Type

Required

Constraint

input.text

String

Yes

Up to 20,000 characters per message. Up to 200,000 characters per task.

{
  "header": {
    "action": "continue-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": { "input": { "text": "Hello, welcome to the speech synthesis service." } }
}

Constraints

  • The interval between two continue-task calls must be < 20 seconds. Otherwise, a task-failed(IdleTimeout) error occurs, but the connection is retained and you can send new tasks.

  • The server-side passes data through in sequence and automatically segments it into sentences. Incomplete sentences are buffered by the engine until a full sentence is formed, a flush is received, or a finish-task is received.

  • If input.text is missing, an InvalidParameter: payload.input.text is required error is returned. An empty string "" is accepted, but no audio is generated.

  • Note: The upstream service counts characters based on UTF-16, where each Chinese character occupies 2 bytes. Therefore, the actual limit for a single request is approximately 10,000 Chinese characters. If this limit is exceeded, the service returns an InvalidParameter error.

3. finish-task — End the task (required)

When to send: Send this after all text has been sent.

Response event: remaining BINARY audio frames, followed by task-finished.

payload field

Type

Required

Value

Description

input

Object

Yes

{}

For a normal task completion, send an empty object.

input.directive

String

No

Only cancel

Cancels the current task. Other non-empty values return an InvalidParameter error.

Normal completion

{
  "header": { "action": "finish-task", "task_id": "550e8400-...", "streaming": "duplex" },
  "payload": { "input": {} }
}
  • The service first flushes the text normalization buffer (if enabled), and then the engine forces synthesis of all buffered content, including any trailing sentence fragments.

  • After sending, you must continue to receive audio until task-finished.

  • The server-side wait for synthesis after finish-task has no timeout, and long text will not be truncated.

Cancel the task (directive: cancel)

{
  "header": { "action": "finish-task", "task_id": "550e8400-...", "streaming": "duplex" },
  "payload": { "input": { "directive": "cancel" } }
}
  • This is the opposite of a normal termination: it immediately returns task-finished, stops outputting subsequent audio, and discards unsynthesized buffered content.

  • After cancellation, you can start a new task on the same connection without needing to reconnect.

  • The returned usage.characters is 0.

  • Corresponds to streamingCancel() / streaming_cancel() in the Model Studio SDK.

Canceling a task does not mean it is not billed. Text that has already been sent to the engine before cancellation is still counted towards your usage. For more information, see "Billing Rules".

4. flush — Force synthesis of buffered text

Use case: In scenarios involving streaming output from large models, text that does not form a complete sentence is held in a buffer and is not immediately synthesized. The flush action forces synthesis of this buffered content, reducing audio-out latency for sentence fragments.

There are two equivalent ways to send a flush request. They have the same semantic meaning, but their compatibility differs depending on the protocol mode:

Method A: continue-task with input.flush=true (Recommended, supported in both modes)

The streaming_flush() function of the Model Studio SDK emits this type of frame. Note that the input does not include the text field.

{
  "header": { "action": "continue-task", "task_id": "550e8400-...", "streaming": "duplex" },
  "payload": { "input": { "flush": true } }
}

Behavior

  • result-generatedIt first flushes the text normalization buffer (if enabled), then instructs the engine to force synthesis. You will immediately receive a event and a binary audio frame for the sentence fragment.

  • The task is still in progress, and you can continue with continue-task.

  • If there is no content to synthesize, this is a safe, no-op action and no downstream events are triggered.

  • Flushing too frequently can result in choppy audio. We recommend using this action only when you need to minimize audio-out latency.

  • Mutually exclusive with word_timestamp_enabled: Sending a flush request when word-level timestamps are enabled returns an InvalidParameter error (because segmentation prevents the timestamps from being continuous).

  • Trailing sentence fragments will not be lost: finish-task is guaranteed to flush the entire buffer, so you do not need to flush before the task ends.

Server-side events (downstream)

The downstream consists of four types of TEXT events and binary audio frames. All TEXT events use a common header/ payload envelope.

Please ignore unknown fields. The service is designed for forward compatibility, so new fields will not break existing integrations.

1. task-started — Task confirmation

{
  "header": { "event": "task-started", "task_id": "550e8400-...", "attributes": {} },
  "payload": {}
}

Field

Type

Description

header.event

String

Fixed value: task-started.

header.task_id

String

Echoes your task_id.

header.attributes

Object

Always an empty object.

payload

Object

Always an empty object.

Send a continue-task message only after receiving this event.

2. result-generated — Sentence-level metadata

{
  "header": { "event": "result-generated", "task_id": "550e8400-..." },
  "payload": {
    "output": {
      "type": "sentence-end",
      "original_text": "Hello, welcome to the speech synthesis service.",
      "sentence": {
        "index": 0,
        "words": [
          { "text": "你", "begin_index": 0, "end_index": 1, "begin_time": 0,   "end_time": 263 },
          { "text": "好", "begin_index": 1, "end_index": 2, "begin_time": 263, "end_time": 520 }
        ]
      }
    },
    "usage": { "characters": 14 }
  }
}

output.type values

Type

Description

Followed by an audio frame?

Is words[] non-empty?

sentence-begin

The sentence begins.

No

No

sentence-synthesis

Audio chunk (can occur multiple times for the same sentence).

Yes, immediately followed by a binary frame.

No (always an empty array)

sentence-end

The sentence ends.

No

Non-empty only if word_timestamp_enabled=true.

Field descriptions

Field

Type

Availability

Description

output.type

String

Always present

The sub-event type.

output.original_text

String

sentence-begin / sentence-end

The text of the segmented sentence. When text normalization (TN) is enabled, this is the normalized text.

output.sentence.index

Integer

Always present

The sentence index, which is unique within the task and increases monotonically from 0.

output.sentence.words[ ].text

String

See the table above.

The character text.

output.sentence.words[ ].begin_index

Integer

See the table above.

The start position of the character in the sentence (0-indexed).

output.sentence.words[ ].end_index

Integer

See the table above.

The end position of the character in the sentence.

output.sentence.words[ ].begin_time

Integer

See the table above.

The start timestamp of the character's audio in milliseconds, relative to the task start.

output.sentence.words[ ].end_time

Integer

See the table above.

The end timestamp of the character's audio in milliseconds.

payload.usage.characters

Integer

Only in sentence-end

The cumulative number of billable characters up to this point. The final count is provided in the task-finished event.

3. Binary audio frames

  • An audio frame arrives immediately after a result-generated event with type="sentence-synthesis". The frame is encoded according to the format and sample_rate specified in the run-task message.

  • The sentence-begin and sentence-end events are for metadata only and are not followed by an audio frame.

  • Append the frames in the order received to play the audio or write it to a file. Reordering is not required.

  • format=pcm indicates the raw PCM format (int16, little-endian, mono), and you must add a WAV header to save the data as a file.

4. task-finished — Task finished

{
  "header": {
    "event": "task-finished",
    "task_id": "550e8400-...",
    "attributes": {
      "request_uuid": "a1f5c7e93b8d4e2f9c0a6b1d7e4f8c25",
      "upstream_request_uuid": "9c0a6b1d-7e4f-8c25-a1f5-c7e93b8d4e2f",
      "session_id": "3f8a1c92-0d4e-4b77-9c31-6a5f2e8b4d10"
    }
  },
  "payload": { "usage": { "characters": 42 } }
}

Field

Type

Description

header.attributes.request_uuid

String

The server-side trace ID, required for troubleshooting. The getLastRequestId() method in the Model Studio SDK reads this field.

header.attributes.upstream_request_uuid

String / Omitted

The upstream engine request ID.

header.attributes.session_id

String / Omitted

The session ID. We recommend providing this ID for troubleshooting.

payload.usage.characters

Integer

The total number of billable characters for this task (including all segments). When TN is enabled, the count is based on the normalized text. The value is 0 when a cancel action occurs. For more information, see Billing Rules.

Empty fields are omitted from the response, rather than being sent as null. Your application should be tolerant of missing keys.
This event indicates that the task has completed and all audio has been transmitted. You can now close the connection or reuse it to start a new task.

5. task-failed — Task failed

{
  "header": {
    "event": "task-failed",
    "task_id": "550e8400-...",
    "error_code": "TextTooLong",
    "error_message": "Text too long: text length 30000 exceeds 20000 per continue-task",
    "attributes": {
      "request_uuid": "a1f5c7e93b8d4e2f9c0a6b1d7e4f8c25",
      "session_id": "3f8a1c92-0d4e-4b77-9c31-6a5f2e8b4d10"
    }
  },
  "payload": {
    "error": {
      "code": "TextTooLong",
      "message": "Text too long: text length 30000 exceeds 20000 per continue-task",
      "type": "client_error"
    }
  }
}

Field

Type

Description

header.error_code

String

The error code, which is identical to payload.error.code. The on_error/onError callbacks in the Model Studio SDK read this field.

header.error_message

String

The error description, which is identical to payload.error.message.

payload.error.code

String

The error code.

payload.error.message

String

A human-readable error description.

payload.error.type

String

client_error: Indicates an issue with request parameters or calling method. Do not retry the request.
server_error: You can use a backoff and retry strategy.

6. connected — Platform extension frame (extended mode only)

This frame is not sent in strict mode (default). It is sent only when ?protocol=extended is declared in the handshake and does not use the header/payload envelope.
{
  "event": "connected",
  "userId": "1405573632598746",
  "workspaceId": "llm-xxxxxxxx",
  "sessionId": "3f8a1c92-0d4e-4b77-9c31-6a5f2e8b4d10",
  "requestId": "a1f5c7e93b8d4e2f9c0a6b1d7e4f8c25",
  "message": "WebSocket connected, gateway auth passed"
}

This frame provides the sessionId and requestId during connection establishment to facilitate troubleshooting. The message field provides human-readable context and must not be used for programmatic decisions.

Key concepts and limitations

Constraint quick reference

Constraint

Value

Text per continue-task message

≤ 20,000 characters (approx. 10,000 Chinese characters)

Cumulative text per task

≤ 200,000 characters

Interval between text frames within a task

< 20 seconds

Connection idle time (no business messages)

< 60 seconds

Maximum connection duration

3,600 seconds (1 hour)

Concurrent tasks per connection

1 (serial reuse)

Uplink frame type

Must be a TEXT frame

Voice

The voice parameter must be a platform voice ID obtained from the Voice Management interface (for example, 9f2a1c4e-7b30-4d51-8a6c-2e5f1b8d0a37).

Background sound

Specify the background_sound parameter in the payload.parameters of a run-task message to mix a background sound into the synthesized audio.

Background sound

Playback mode

Description

office

Continuous play

Plays a looping office background sound.

office_mix

Random intermittent play

Randomly plays 1- to 2-second segments from one of five office sound clips. These segments are separated by 5- to 10-second intervals where no background sound is added.

Usage constraints and behavior

  • When enabling background sound, you must explicitly set format=pcm or format=wav. The default formats, mp3 and opus, do not support background sound and return an InvalidParameter error.

  • In intermittent mode, an initial 5- to 10-second interval with no background sound precedes the random playback. These intervals only mean that no background sound is mixed in; they do not interrupt or pause the synthesized voice. A short task may finish before the first background sound segment plays.

  • Segment and interval lengths are calculated based on the duration of the task's output audio, not the elapsed wall-clock time. Sending more text within the same task does not restart the timer. A new task starts a new random schedule.

  • The value of background_snr must be in the range of [-5, 40] dB, and only specific values are accepted. If you specify a value, the SNR is fixed. If you do not specify this parameter, the service randomly selects an SNR between 0 and 30 dB and changes it every 10 seconds, with a smooth transition of about 2 seconds. Setting a fixed SNR does not disable the random segments and intervals of the intermittent mode.

  • Background sound parameters are specified in the run-task message and apply to the current task. To change the background sound or SNR, start a new task. Providing an unknown background sound name will result in an InvalidParameter error and will not automatically fall back to voice-only synthesis.

Random intermittent background sound example

Replace <platform voice ID> with an actual platform voice ID. After receiving the task-started message, follow the standard procedure to send text with continue-task and end the task with finish-task. Omit the background_snr parameter to let the service randomly adjust the background volume.

{
  "header": {
    "action": "run-task",
    "task_id": "550e8400-e29b-41d4-a716-446655440000",
    "streaming": "duplex"
  },
  "payload": {
    "parameters": {
      "voice": "<platform voice ID>",
      "format": "pcm",
      "sample_rate": 24000,
      "background_sound": "office_mix",
      "background_snr": 10
    },
    "input": {}
  }
}

Text normalization (TN)

Text normalization converts written forms of numbers, dates, times, amounts, phone numbers, and unit symbols into their spoken-word equivalents before synthesis to prevent incorrect pronunciations, such as reading "12345" as individual digits.

  • TN is disabled by default. Enable it with the X-TTS-TN: enable header or the ?tn=enable query parameter. This is a session-level setting that applies to all tasks within the connection.

  • Streaming behavior: Text is fed into the normalization pipeline character by character. Segments containing numbers or letters are buffered until a punctuation boundary is reached. For this reason, ensure that sentences end with end-of-sentence punctuation (such as ., !, ?, or ;). To force immediate synthesis of a sentence fragment, send a flush signal. The finish-task message always flushes the buffer, so no trailing text is lost.

  • Fail-open: If the normalization component is unavailable, the service automatically falls back to using the original text without returning an error or disconnecting the session. Error handling for TN failures is not required.

Behavior with TN enabled

Item

TN Disabled

TN Enabled

Text sent to the synthesis engine

Your original text.

The normalized text.

result-generated.output.original_text

Segmented original sentence.

Segmented normalized sentence.

words[].begin_index / end_index

Relative to the original sentence.

Relative to the normalized sentence.

usage.characters (billable characters)

Based on the original text.

Based on the normalized text (spoken form is typically longer).

Validation for ≤ 20,000 characters per continue-task

Based on the original text.

Still based on the original text.

Cumulative limit of ≤ 200,000 per task

Based on the original text.

Based on the normalized text.

If you need to map audio timestamps back to the character indices of the original input text, do not enable TN. The service does not provide a mapping between the original and normalized text.
It is not recommended to enable this parameter together with enable_ssml (because TN processes numbers within the tags). It can be enabled together with word_timestamp_enabled.

Timeout matrix

Timeout

Threshold

Trigger

Result

Text interval within a task

20 seconds

No continue-task or finish-task message is received for 20 consecutive seconds during an ongoing task.

The task fails with an IdleTimeout error. The connection remains open for reuse.

Idle timeout

60 seconds

No business messages are exchanged for 60 consecutive seconds.

The server actively closes the connection with close code 4408.

Maximum connection duration

3,600 seconds

The connection has been established for 1 hour.

The service sends a task-finished event and closes the connection with code 1000. Ongoing tasks are not interrupted and will complete before the connection is closed.

Upstream task confirmation

30 seconds

The upstream engine does not confirm the task within 30 seconds.

A task-failed(EngineUnavailable) error occurs, but the connection is kept open.

Synthesis after finish-task

No timeout

—

Long texts are not truncated. The service waits until the engine finishes processing.

Heartbeat

Recommended to send a WS ping every 15–30 seconds.

Sent by the client.

The server automatically responds with a pong.

Important: Heartbeats (ping/pong) do not reset the idle timeout timer. An idle connection that is only sending heartbeats will still be closed after 60 seconds. Heartbeats maintain the network link through intermediate proxies, but they are separate from the service's idle resource management.

Concurrency limit

  • The gateway enforces a workspace-level limit on the number of concurrent active WebSocket connections.

  • If the limit is exceeded, the handshake returns an HTTP 429 response (which may appear as close code 1006 in a browser). If a connection is rejected after the upgrade, the service closes it with close code 4429.

  • The default quota is 5 concurrent WebSocket connections per workspace. A connection occupies a quota slot from establishment until it is closed.

  • Idle connections count toward your quota because slots are not automatically released when synthesis is inactive. Close connections when they are no longer needed.

  • To request a higher concurrency quota, contact the platform.

Error codes and close codes

Business error codes (task-failed)

error.code

HTTP

Close code

Type

Description

InvalidParameter

400

—

client_error

Parameter validation failed: out-of-range format / sample_rate / volume / rate / pitch / bit_rate / seed, invalid opus sample rate, inconsistent task_id, task already in progress, duplicate text in an SSML context, invalid action, or an uplink BINARY frame.

Unauthorized

401

4401

client_error

The credential is invalid, missing, or has expired.

Forbidden

403

4403

client_error

You do not have permission to use the specified voice, or the voice has not passed review.

NotFound

404

—

client_error

The specified voice does not exist or is not visible to your account. The service does not distinguish between these two cases to prevent resource enumeration.

TextTooLong

413

—

client_error

The text in a single request exceeds 20,000 characters, or the cumulative text for a single task exceeds 200,000 characters.

RateLimitExceeded

429

4429

client_error

The request exceeded the concurrent connection limit, or the request rate is too high.

IdleTimeout

—

4408

client_error

The text interval within a task exceeds 20s (task-failed) or the business connection is idle for more than 60s (disconnection 4408)

InternalError

500

1011

server_error

An internal server error occurred.

EngineUnavailable

503

1011

server_error

The upstream engine is unavailable or timed out.

The type field has two possible values. For a client_error, you need to modify your parameters or request logic, and a retry is pointless. For a server_error, retry using an exponential backoff strategy.

WebSocket close codes

Close code

Description

Recommended action

1000

Normal closure, including the 1-hour expiration.

To send more requests, establish a new connection.

1001

The server instance is shutting down due to a deployment or scale-in event.

Reconnect immediately. Your request will be routed to a new instance. No backoff is needed.

1006

The connection was rejected during the handshake phase. Browsers may not report the specific HTTP status code.

Use fetch to probe the same path to differentiate between 401 / 400 / 429 status codes. Provide the requestId from the handshake URL for troubleshooting.

1011

An internal server error occurred, or the upstream engine failed.

Reconnect using an exponential backoff strategy.

4401

Authentication failed or the credential has expired.

Refresh your credential and reconnect.

4403

Permission denied for the requested voice.

Check the ownership and permissions of the voice. Retrying is pointless.

4408

Idle timeout (60 seconds).

This is a normal cleanup procedure. Reconnect as needed.

4429

Concurrency limit exceeded.

Notify the user and retry the connection after a delay.

Failures during the handshake phase do not generate an application-level close frame. A missing or invalid credential returns a 401 response, an invalid protocol value returns a 400 response, and rate limiting returns a 429 response. In a browser, all these errors are typically observed only as close code 1006. Therefore, we highly recommend you always include a requestId in the handshake URL to facilitate troubleshooting.