Bidirectional Streaming Synthesis

WebSocket Bidirectional Streaming Speech Synthesis

Overview

Send incremental text and receive synthesized audio concurrently over one WebSocket connection. This is suitable for applications such as progressively generated language model responses. The service submits text for synthesis sentence by sentence and submits any remaining text when the client finishes input.

Unlike WebSocket Synthesis, which accepts complete text requests, this API has a separate endpoint and session protocol. Controls are JSON Text messages; audio is Binary, without audioBase64. A connection supports one active session at a time. After a terminal event, start another session with a new sessionId; parallel sessions require separate connections.

Integration Flow

  1. Create a speech synthesis application in the console, obtain its appId and service secret, and prepare an available prebuilt or registered voice name.
  2. Request a bidirectional streaming token using the application signature.
  3. Connect to the returned wsUrl with the token query parameter before the token expires.
  4. Send session.start, wait for session.started, and then send ordered text.append messages.
  5. Continuously receive audio while sending text. Send input.finish after the last text fragment.
  6. The session ends with session.finished, session.canceled, or session.failed.

Obtain a Connection Token

GET https://tts.ilivedata.com/api/v2/speech/synthesis/bidirection-token
Header Required Description
X-AppId Yes Application ID from the console
X-TimeStamp Yes UTC time, for example 2026-11-25T08:00:00Z
Authorization Yes Request signature calculated with the service secret

Follow the GET request without a body rules in Request Signature. Example string to sign, using \n between lines and no trailing newline:

GET
tts.ilivedata.com
/api/v2/speech/synthesis/bidirection-token
X-AppId:81900001
X-TimeStamp:2026-11-25T08:00:00Z

Authorization = Base64(HMAC-SHA256(secretKey, StringToSign)). For another regional endpoint, sign the actual token request Host. Keep the service secret on your application server, not in browser or mobile client code.

Example response (timestamps are illustrative):

{
  "token": "{jwt}",
  "expiresIn": 60,
  "expiresAt": 1795593660,
  "wsUrl": "wss://tts.ilivedata.com/api/v2/speech/synthesis/bidirection"
}

expiresIn is in seconds; expiresAt is Unix time in seconds. Use the actual returned wsUrl:

wss://tts.ilivedata.com/api/v2/speech/synthesis/bidirection?token={jwt}

Tokens are bound to the endpoint path. A token from the old /ws-token endpoint cannot be used here. Application identity comes from the token; do not send appId in JSON messages. Tokens are validated when connecting. Expiration does not terminate an established connection; obtain a fresh token before reconnecting.

Client Messages

Send each control as one JSON object in a WebSocket Text message.

Common field Type Required Description
event String Yes One of the four client events below
eventId String Yes Client message identifier; UUID recommended. Nonempty, up to 128 UTF-8 bytes. It is not an automatic deduplication or resume key
sessionId String Yes Client session identifier; UUID recommended. Nonempty, up to 128 UTF-8 bytes. Never reuse it to create another session on the same connection

session.start: Create a Session

{
  "event": "session.start",
  "eventId": "c1",
  "sessionId": "session-001",
  "protocolVersion": 1,
  "config": {
    "language": "en-US",
    "voice": {"name": "juvenile"},
    "output": {"format": "pcm"},
    "segmentation": {"splitOnComma": false}
  }
}
Field Type Required Description
protocolVersion Integer Yes Must be 1
config Object Yes Session configuration; immutable after creation
config.language String No Recommended, such as en-US or zh-CN. If omitted, detected from the first actual sentence and fixed for the session. See Languages; explicit pt-BR is currently rejected by this API
config.voice.name String Yes Public name of a prebuilt voice or registered voice, not an engine-specific voice ID
config.output Object No Defaults to PCM
config.output.format String No pcm (default), mp3, or opus; wav is unsupported
config.output.sampleRate Integer No Must be 24000
config.output.channels Integer No Must be 1
config.output.sampleFormat String No If present, must be s16le, describing internal PCM samples. For compressed output, use the actual format in session.started.audio
config.segmentation.splitOnComma Boolean No Defaults to false. Enables comma boundaries subject to minimum fragment rules; not every comma immediately triggers synthesis

Only the listed config fields are supported. Do not send the old request body: voice.audio, voice.model, engine, speed, loudnessLufs, output.fileFormat, fileOutput, and persist are not supported.

text.append: Append Text

{"event":"text.append","eventId":"c2","sessionId":"session-001","textSeq":1,"text":"Hello, welcome to bidirectional speech synthesis!"}
Field Type Required Description
textSeq Integer Yes Starts at 1 for every session and increments strictly by one
text String Yes Nonempty text fragment: a word, sentence, or text block

Append only after session.started. Waiting for the matching text.accepted before the next append is recommended. An acknowledgment means input acceptance, not synthesis completion. Text input and audio delivery can run concurrently.

The service uses sentence punctuation and a default maximum of 200 Unicode code points per sentence; English periods are evaluated with following text. There is no short idle timer that automatically submits an unfinished tail. Send input.finish to submit the remainder.

input.finish: Finish Input

{"event":"input.finish","eventId":"c3","sessionId":"session-001"}

The service returns input.finished, submits any remaining text, and continues delivering audio. Do not append more text; wait for the terminal event. Finishing without any text is allowed and produces an empty successful session.

session.cancel: Cancel a Session

{"event":"session.cancel","eventId":"c4","sessionId":"session-001","reason":"user_interrupt"}

reason is optional business context. Immediately stop sending text and clear unplayed client audio. The service cancels upstream synthesis and drops unsent audio. Wait for session.canceled or connection closure before starting another session; sending the cancellation message alone does not authorize immediate reuse.

Server Control Events

All controls are Text JSON messages.

Common field Type Description
event String Event name
eventId String Server-generated event identifier
sessionId String Client session identifier; may be absent if the original message could not be parsed
requestEventId String Client eventId when the event directly responds to a request; otherwise may be absent
Event Additional fields Meaning
session.started protocolVersion, audio, segmentation, limits Ready for text; initialize the player using audio
text.accepted textSeq Text with this sequence number was accepted
input.finished lastTextSeq Input closed and the remainder submitted; synthesis may still be running
sentence.started sentenceId, text Audio for this sentence is about to start; sentenceId starts at 1; text is the actual sentence
sentence.finished sentenceId, audioBytes All audio for this sentence was submitted for delivery, not necessarily played
session.finished sentenceCount, audioBytes All sentences completed; successful terminal event
session.canceled None Canceled terminal event
session.failed code, message Failed terminal event; no more text can be appended
error code, message Message-level error, generally leaving the active session running; correct the message according to code

Example PCM session start:

{
  "event": "session.started",
  "eventId": "s1",
  "sessionId": "session-001",
  "requestEventId": "c1",
  "protocolVersion": 1,
  "audio": {"format":"pcm","sampleRate":24000,"channels":1,"sampleFormat":"s16le"},
  "segmentation": {"splitOnComma":false,"maxSentenceChars":200},
  "limits": {
    "maxSessionChars":100000,
    "maxTextMessageBytes":16384,
    "maxPendingTextChars":8000,
    "maxPendingSentences":32,
    "maxSessionDurationMs":600000
  }
}

Completion and failure examples:

{"event":"sentence.finished","eventId":"s2","sessionId":"session-001","sentenceId":1,"audioBytes":48000}
{"event":"session.finished","eventId":"s3","sessionId":"session-001","sentenceCount":1,"audioBytes":48000}
{"event":"session.failed","eventId":"s4","sessionId":"session-002","code":"INVALID_CONFIG","message":"voice.name is required"}

Binary Audio and Ordering

Binary audio has no custom application header, sessionId, sentenceId, or Base64 wrapper. Associate audio using the ordered control events:

Client                                      Server
session.start ---------------------------->
              <---------------------------- session.started
text.append(textSeq=1) ------------------->
              <---------------------------- text.accepted
              <---------------------------- sentence.started(sentenceId=1)
              <---------------------------- Binary audio, one or more messages
              <---------------------------- sentence.finished(sentenceId=1)
text.append(textSeq=2) ------------------->
              <---------------------------- text.accepted
input.finish ----------------------------->
              <---------------------------- input.finished
              <---------------------------- sentence.started(sentenceId=2)
              <---------------------------- Binary audio, one or more messages
              <---------------------------- sentence.finished(sentenceId=2)
              <---------------------------- session.finished

Input acknowledgments may interleave with another sentence’s audio. Read and write concurrently, rather than waiting until all text is sent before reading audio. Audio for each sentence is always between its sentence.started and sentence.finished events, without interleaving with the next sentence’s audio.

format Returned audio Client handling
pcm 24000Hz, mono, signed 16-bit little-endian PCM without a WAV header Each message has an even byte count. Use a raw PCM player or add a WAV header after collection
mp3 24000Hz, mono, 64kbps MP3 Feed Binary messages in sentence order into an MP3 streaming decoder
opus 24000Hz, mono, 64kbps Opus in an Ogg container Use an Ogg Opus decoder, not a raw Opus or WebM decoder

For MP3/Opus, session.started.audio returns container (mp3 or ogg), bitrateKbps:64, and encodingScope:"sentence" instead of sampleFormat. Sentences are independently encoded and delivered incrementally. A Binary message may contain only part of an audio frame or container, so do not decode every message as a standalone file.

Decode per sentence or use a player supporting consecutive MP3 / chained Ogg streams. Gapless playback across sentences is not guaranteed; MP3 encoding delay and padding may add brief pauses. audioBytes counts bytes in the selected output format, not duration.

This API does not return a file URL, file_ready, or file_error. session.finished indicates submission of all audio for delivery, not playback completion, and does not wait for background file archival.

Connection Reuse, Quotas, and Disconnections

  • One active session per connection. After a terminal event, use a new sessionId to start the next session. A failed start also requires a fresh ID on that connection.
  • Use separate connections for parallel sessions. Active sessions share the application concurrency quota with other streaming synthesis APIs; extra connections do not bypass quotas.
  • Defaults: 100000 Unicode code points and 10 minutes per session; 16KiB per complete UTF-8 JSON message; 8000 pending text code points; 32 pending sentences. Use session.started.limits for actual session limits.
  • Default maximum: 1000 sessions per connection. Connection or input inactivity can time out after about 60 seconds. Keep receiving after input.finished.
  • Your WebSocket library must respond to Ping/Pong automatically. Defaults: Ping every 20 seconds and close if no Pong within 10 seconds. Heartbeats do not replace text input.
  • Read audio continuously and use a bounded playback buffer. Cancel or slow text input when the client falls behind.
  • No resume or automatic recovery after disconnect. Obtain a fresh token, reconnect, and use a new sessionId. Resending previously synthesized text can produce duplicate audio and usage.

Errors and Close Codes

code Meaning and action
INVALID_MESSAGE / UNKNOWN_EVENT Correct the JSON Text message or event name
UNSUPPORTED_VERSION Use protocolVersion 1 and a new sessionId
INVALID_CONFIG / UNSUPPORTED_AUDIO_FORMAT Correct unsupported configuration and start a new session
SESSION_BUSY Wait for or cancel the active session on this connection
SESSION_MISMATCH / SESSION_CLOSED Wrong or closed session; stop sending old-session messages
INVALID_TEXT_SEQUENCE Correct textSeq using the error message; rejected input does not advance the expected sequence
INPUT_CLOSED Input has already finished
SESSION_TEXT_LIMIT / INPUT_BUFFER_FULL Session text or queue limit exceeded; reduce input or slow down
RATE_LIMITED / ENCODER_BUSY Application or audio encoder capacity exceeded; retry later with a new session
INPUT_IDLE_TIMEOUT / PROCESSING_TIMEOUT / SYNTHESIS_TIMEOUT / SESSION_TIMEOUT Input, preparation, model synthesis, or total session deadline exceeded
AUDIO_CONFIG_MISMATCH / SYNTHESIS_FAILED / SLOW_CONSUMER Invalid upstream audio, synthesis failure, or audio backlog exceeded; record sessionId and handle the terminal event

Possible WebSocket close codes: 1008 (authentication, policy, or cancellation cleanup failure), 1009 (message too large), and 1013 (slow consumer or queue congestion). Authentication failures may not return a business JSON event. Clear playback queues on disconnect and reconnect with a fresh token when appropriate.

Python Example

Install python3 -m pip install websockets. Obtain a token on your application server, then pass it through TTS_WS_TOKEN and set TTS_WS_URL to the returned wsUrl. The example uses default PCM, saves raw PCM, and wraps it as WAV locally; it does not request a server file URL.

import asyncio
import json
import os
import uuid
import wave
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

import websockets

async def main():
    url = urlsplit(os.environ["TTS_WS_URL"])
    query = dict(parse_qsl(url.query))
    query["token"] = os.environ["TTS_WS_TOKEN"]
    uri = urlunsplit((url.scheme, url.netloc, url.path, urlencode(query), ""))
    session_id = str(uuid.uuid4())
    acks = {}
    chunks = ["Hello, welcome to bidirectional synthesis!", "This is the second text fragment!"]

    async with websockets.connect(uri, open_timeout=15) as ws:
        async def send(event, **fields):
            await ws.send(json.dumps({"event": event, "eventId": str(uuid.uuid4()),
                                      "sessionId": session_id, **fields}, ensure_ascii=False))

        await send("session.start", protocolVersion=1,
                   config={"language": "en-US", "voice": {"name": "juvenile"},
                           "output": {"format": "pcm"}})
        started = json.loads(await ws.recv())
        if started["event"] != "session.started":
            raise RuntimeError(started)
        if started["audio"] != {"format": "pcm", "sampleRate": 24000,
                                "channels": 1, "sampleFormat": "s16le"}:
            raise RuntimeError("Unexpected audio configuration")

        async def produce():
            for seq, text in enumerate(chunks, 1):
                ack = asyncio.get_running_loop().create_future()
                acks[seq] = ack
                await send("text.append", textSeq=seq, text=text)
                await ack
            await send("input.finish")

        producer = asyncio.create_task(produce())
        sentence_id = None
        try:
            with open("result.pcm", "wb") as output:
                async for message in ws:
                    if isinstance(message, bytes):
                        if sentence_id is None or len(message) % 2:
                            raise RuntimeError("Unexpected PCM packet")
                        output.write(message)
                        continue
                    event = json.loads(message)
                    kind = event["event"]
                    if kind == "text.accepted":
                        acks.pop(event["textSeq"]).set_result(None)
                    elif kind == "sentence.started":
                        sentence_id = event["sentenceId"]
                    elif kind == "sentence.finished":
                        sentence_id = None
                    elif kind == "session.finished":
                        break
                    elif kind in ("error", "session.failed", "session.canceled"):
                        raise RuntimeError(event)
                else:
                    raise RuntimeError("Connection closed before session finished")
            await producer
        finally:
            producer.cancel()
            await asyncio.gather(producer, return_exceptions=True)

    with wave.open("result.wav", "wb") as wav, open("result.pcm", "rb") as pcm:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(24000)
        while block := pcm.read(65536):
            wav.writeframesraw(block)

asyncio.run(asyncio.wait_for(main(), timeout=660))

The voice name juvenile is illustrative; replace it with one available to your application. For user interruptions, send session.cancel and clear local playback queues. Wait for session.canceled before starting the next session on the same connection.