Messages
{
"action": "<string>",
"model": "<string>",
"targetText": "<string>",
"locale": "<string>",
"voicePromptId": "<string>"
}Text-to-Speech
Generate Audio Streamed
Send one complete text and stream the generated audio back over a WebSocket
Overview
You send one complete text, and the audio streams out to you as it is generated — delivered incrementally as base64-encoded chunks, so playback can begin before the full generation finishes. This is the default text-to-speech API and the fastest one. Open the connection once and keep sending requests on it: each request skips the HTTP and TLS setup, and you can run several generations on one connection at the same time. Jump to the code examples for a client with the SDK and one without it.This endpoint takes the same generation parameters as the REST endpoint for testing, which is meant for quick tests and one-off files. It supports more formats than REST, including
wav and raw s16le.If your text is not complete up front — for example it arrives token-by-token from an LLM, as in a voice agent — use the LLM Integration / Voice Agents API (
/ws) instead, which accepts text as it is produced. This page documents the single-request text-to-speech protocol (/open).Connection
Connect to the/open endpoint with your API key:
| Region | URL |
|---|---|
| US | wss://wsgw.deepdub.ai/open |
| EU | wss://wsgw.eu.deepdub.ai/open |
x-api-key header or query parameter.
Request format
Send a JSON message on the WebSocket connection:Playback speed multiplier, between 0 and 2. Mutually exclusive with
targetDuration — sending both is rejected.Output sample rate in Hz. One of
8000, 16000, 22050, 24000, 32000, 36000, 44100, or 48000; any other value is rejected. Internal generation is 48 kHz, resampled to the requested rate. Defaults to 8000 Hz for mulaw if not specified.Accent blending parameters. See AccentControl below.
Target speaker gender,
male or female. Used for language-specific handling such as Hebrew diacritics. Other values are ignored rather than rejected.Return the diacritized (menukad) form of the Hebrew
targetText alongside the audio. When enabled, the first audio chunk carries a diacritized field.Whether Deepdub may record this request’s text in its server-side logs. Set to
false for confidential scripts to keep the text out of the logs.outputDiacritized is available on request rather than enabled for every account. Contact [email protected] to have it turned on before integrating against it.Example request
{
"action": "text-to-speech",
"model": "dd-etts-4.0",
"targetText": "Welcome to Deepdub's real-time text to speech API.",
"locale": "en-US",
"voicePromptId": "bd1b00bb-be1c-4679-8eaa-0fcbfd4ff773",
"format": "wav",
"sampleRate": 16000
}
Response format
Audio chunks
Audio is delivered as a series of JSON messages. Each chunk contains a portion of the audio data:The generation ID for this request. Use this to correlate chunks with requests when running multiple generations on the same connection.
Diacritized (menukad) Hebrew text for the request. Sent only when
outputDiacritized was enabled, and only on the first audio chunk — later chunks omit the field entirely.Example response stream
Initial acknowledgement:{
"data": "",
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9",
"isFinished": false
}
{
"index": 0,
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9",
"data": "//uQxAAAAAANIAAAAAExBTUUzLjEwMFVVVVVVVVVV...",
"isFinished": false
}
{
"index": 1,
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9",
"data": "HAAYABgAGAAgACAA...",
"isFinished": false
}
{
"index": 2,
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9",
"data": "AAAAAAAAAA==",
"isFinished": true
}
outputDiacritized is enabled:
{
"index": 0,
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9",
"data": "//uQxAAAAAANIAAAAAExBTUUzLjEwMFVVVVVV...",
"isFinished": false,
"diacritized": "שָׁלוֹם עוֹלָם"
}
Error responses
When an error occurs, the WebSocket sends a JSON error message:Error category. One of:
RateLimit, MaxExceeded, InsufficientCredits, InvalidInput. Present on requests rejected up front; errors raised later, once generation is already under way, carry only error and generationId.{
"error": "Rate limit exceeded",
"errorType": "RateLimit",
"generationId": "4da9902b-9141-4fb7-9efb-d616ce266ed9"
}
| Error type | Description |
|---|---|
RateLimit | Too many concurrent requests. Reduce request frequency. |
MaxExceeded | Maximum generation minutes reached for your plan. |
InsufficientCredits | Account has insufficient credits. Top up your balance. |
InvalidInput | Invalid request parameters. Check your request body. |
The free trial key is additionally capped at 10 generations per IP per day. Once that is used up, requests fail with
errorType: "RateLimit" and a message of the form Free tier quota exceeded (used: 10). Please get an API key to continue. Get your own API key to lift the cap.Accent control
Blend accents between two locales using theaccentControl object:
{
"accentControl": {
"accentBaseLocale": "en-US",
"accentLocale": "fr-FR",
"accentRatio": 0.75
}
}
| Field | Type | Description |
|---|---|---|
accentBaseLocale | string | Base accent locale (e.g., en-US) |
accentLocale | string | Target accent to blend (e.g., fr-FR) |
accentRatio | number | Blend ratio from 0.0 (base only) to 1.0 (target only) |
Supported output formats
Audio chunks are delivered as base64-encoded data in JSON messages.| Format | Description |
|---|---|
wav | Uncompressed PCM in a WAV container (default) |
mp3 | MP3 |
opus | Opus |
mulaw | 8-bit μ-law, common in telephony |
s16le | Raw signed 16-bit little-endian PCM, no container |
Sample rates
Valid values are8000, 16000, 22050, 24000, 32000, 36000, 44100, and 48000 Hz. The internal generation runs at 48 kHz and is resampled to the requested rate. If no sample rate is specified, mulaw defaults to 8000 Hz.
REST vs Generate Audio Streamed
| Feature | REST endpoint for testing | Generate Audio Streamed |
|---|---|---|
| Delivery | Streaming HTTP response (chunked audio bytes) | Chunked audio delivered incrementally as base64-encoded JSON messages |
| Formats | mp3, opus, mulaw | wav (default), mp3, opus, mulaw, s16le |
| Text streamed in | No | No — use LLM Integration / Voice Agents |
| Default format | mp3 | wav |
| Default mulaw sample rate | 8000 Hz | 8000 Hz |
| Best for | Testing and one-off files where latency does not matter | Default: real-time playback, lowest latency |
Code examples
With the SDK
- Python
- JavaScript
import asyncio
from deepdub import DeepdubClient # pip install deepdub
client = DeepdubClient(api_key="dd-00000000000000000000000065c9cbfe")
async def streaming_tts():
audio_data = bytearray()
async with client.async_connect() as conn:
async for chunk in conn.async_tts(
text="Hello, this is streamed text input.",
voice_prompt_id="bd1b00bb-be1c-4679-8eaa-0fcbfd4ff773",
model="dd-etts-4.0",
locale="en-US",
format="wav",
sample_rate=16000,
):
audio_data.extend(chunk)
print(f"Received chunk: {len(chunk)} bytes")
with open("output.wav", "wb") as f:
f.write(audio_data)
print(f"Total audio: {len(audio_data)} bytes")
asyncio.run(streaming_tts())
const fs = require("fs");
const { DeepdubClient } = require("@deepdub/node"); // npm install @deepdub/node
async function streamingTts() {
const deepdub = new DeepdubClient("dd-00000000000000000000000065c9cbfe");
await deepdub.connect();
const chunks = [];
for await (const chunk of deepdub.asyncTts("Hello, this is streamed text input.", {
locale: "en-US",
voicePromptId: "bd1b00bb-be1c-4679-8eaa-0fcbfd4ff773",
model: "dd-etts-4.0",
format: "wav",
})) {
chunks.push(chunk);
console.log(`Received chunk: ${chunk.length} bytes`);
}
const audio = Buffer.concat(chunks);
fs.writeFileSync("output.wav", audio);
console.log(`Total audio: ${audio.length} bytes`);
deepdub.disconnect();
}
streamingTts();
Without the SDK
Any WebSocket client works. Send the request as JSON, then decode the base64data of each message until isFinished is true. The first message is an acknowledgement with empty data.
- Python
- JavaScript
import asyncio
import base64
import json
import websockets # pip install "websockets>=14"
async def streaming_tts():
headers = {"x-api-key": "dd-00000000000000000000000065c9cbfe"}
async with websockets.connect("wss://wsgw.deepdub.ai/open", additional_headers=headers) as ws:
await ws.send(json.dumps({
"action": "text-to-speech",
"model": "dd-etts-4.0",
"targetText": "Hello, this is streamed text input.",
"locale": "en-US",
"voicePromptId": "bd1b00bb-be1c-4679-8eaa-0fcbfd4ff773",
"format": "wav",
"sampleRate": 16000,
}))
audio_data = bytearray()
while True:
msg = json.loads(await ws.recv())
if msg.get("error"):
raise RuntimeError(msg)
if msg.get("data"):
audio_data += base64.b64decode(msg["data"])
print(f"Received chunk {msg.get('index')}")
if msg.get("isFinished"):
break
with open("output.wav", "wb") as f:
f.write(audio_data)
print(f"Total audio: {len(audio_data)} bytes")
asyncio.run(streaming_tts())
const fs = require("fs");
const WebSocket = require("ws"); // npm install ws
const ws = new WebSocket("wss://wsgw.deepdub.ai/open", {
headers: { "x-api-key": "dd-00000000000000000000000065c9cbfe" },
});
const chunks = [];
ws.on("open", () => {
ws.send(JSON.stringify({
action: "text-to-speech",
model: "dd-etts-4.0",
targetText: "Hello, this is streamed text input.",
locale: "en-US",
voicePromptId: "bd1b00bb-be1c-4679-8eaa-0fcbfd4ff773",
format: "wav",
sampleRate: 16000,
}));
});
ws.on("message", (raw) => {
const msg = JSON.parse(raw);
if (msg.error) throw new Error(msg.error);
if (msg.data) {
chunks.push(Buffer.from(msg.data, "base64"));
console.log(`Received chunk ${msg.index}`);
}
if (msg.isFinished) {
const audio = Buffer.concat(chunks);
fs.writeFileSync("output.wav", audio);
console.log(`Total audio: ${audio.length} bytes`);
ws.close();
}
});
Messages
{
"action": "<string>",
"model": "<string>",
"targetText": "<string>",
"locale": "<string>",
"voicePromptId": "<string>"
}Text to speech
type:object
