# Stream speech (WebSocket)

> wss /api/v1/tts/ws/ streams audio while you send text in chunks. Messages, init parameters, formats, credits, close codes and examples.

## Endpoint

`wss://moknah.io/api/v1/tts/ws/`

A two-way connection: send text progressively (for example as an LLM produces it) and receive audio bytes continuously.

Requirements: an API key whose allowed services include `tts_ws`, and a positive credit balance.

## Authentication

Send `Authorization: Bearer YOUR_API_KEY` on the handshake. Browsers cannot set that header, so `?api_key=YOUR_API_KEY` in the URL is accepted too.

## Session flow

1. Connect.
2. Send one `init` message.
3. Wait for `{"status": "ready", ...}`.
4. Send `text` messages.
5. Send `stop` when there is no more text.
6. Read binary audio frames until `{"type": "end_of_stream"}`. Then close.

One stream per account can be open at a time.

## Messages you send

All messages are JSON text frames. Binary frames are rejected.

### init

```json
{
  "type": "init",
  "voice_id": 1710,
  "output_format": "pcm_24000",
  "prerecording": 1,
  "language": "ar",
  "voice_settings": {"mode": "emotion"}
}
```

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | string | yes | | `init`. |
| `voice_id` | integer | yes | | A voice the key can use, from [List voices](voices.md). |
| `output_format` | string | no | `pcm_24000` | Any text to speech format except `wav_*`. See [Generate speech](tts-generate.md#output-formats). Advanced engine voices stream as `pcm_*` or `mp3_*` only. |
| `prerecording` | integer | no | `1` | `1` Basic, `2` Arabic Tashkeel, `3` AI Poet. `2` and `3` are for Arabic only. |
| `language` | string | no | | ISO 639-1 content language. Same rules as the REST endpoint. |
| `voice_settings` | object | no | `{}` | See below. |

A second `init` on the same connection is answered with an error.

### Voice settings

Standard engine voices:

| Key | Allowed values | Description |
| --- | --- | --- |
| `mode` | `emotion`, `quality`, `studio` | Default `emotion`, which has the lowest latency. Any other value is rejected. |
| `fast_mode` | `0`, `1`, `2` | `1` or `2` switches to the low-latency model and overrides `mode` for pricing. `0` is off. |
| `temperature` | 0 to 100 | Variability. |
| `similarity` | 0 to 100 | How closely the result follows the original voice. Note the name: the REST endpoint calls it `voice_similarity`. |
| `speed` | number | Speaking rate. |

Only `mode` and `fast_mode` are validated when the stream starts. Keep the other values inside the ranges given for the REST endpoint.

Advanced engine voices take `context`, `setting`, `style` and `pace`, as in the REST endpoint, and stream sentence by sentence.

### text

```json
{"type": "text", "data": "مرحبا بكم."}
```

At most 2,000 characters per message. For the fastest first audio, end each chunk with sentence punctuation (`.`, `!`, `?`, `؟`) or a new line: the voice waits for a sentence boundary to get the intonation right.

### stop

```json
{"type": "stop"}
```

The server finishes the text it holds, sends the remaining audio, then sends `end_of_stream`.

## Messages you receive

| Frame | Meaning |
| --- | --- |
| Binary | Audio bytes in the requested `output_format`. MP3 frames can be written straight to a file; PCM frames are raw 16-bit little-endian mono samples. |
| `{"status": "ready", "message": "..."}` | The stream is initialized. Start sending text. |
| `{"type": "end_of_stream"}` | Every audio byte has been delivered. Safe to close. |
| `{"error": "..."}` | A problem with the last message or with the stream. Some errors end the stream; see below. |
| `{"error": "...", "code": "CONTENT_REJECTED"}` | The text was refused by the content policy check. |

Error messages you can receive:

| Message | Cause |
| --- | --- |
| `Not initialized. Send init message first.` | A `text` or `stop` arrived before `init`. |
| `Already initialized.` | A second `init`. |
| `Missing required parameter: voice_id` | `init` without a voice. |
| `Invalid or inaccessible voice_id.` / `Voice not allowed for this API key.` | The voice does not exist, is not available to the account, or is of the other voice type. |
| `Invalid output_format. Use one of: ...` | Unknown format, or a `wav_*` format. |
| `mode must be one of: emotion, quality, studio.` | Invalid `mode`. |
| `fast_mode must be 0, 1 or 2.` | Invalid `fast_mode`. |
| `Chunk too large. Maximum 2000 characters per chunk.` | A `text` message was too long. The stream stays open. |
| `Rate limit: Processing queue is full. Please slow down.` | Text is arriving faster than it can be voiced. |
| `Insufficient credits during stream` | The balance ran out. Audio already generated is still delivered, then the stream ends. |
| `Audio generation failed. Please try again.` | Generation failed. The connection closes with `3011`. |

## Close codes

| Code | Meaning |
| --- | --- |
| 1000 | The stream completed normally. |
| 3011 | Audio generation failed. Retry. |
| 4001 | No API key was sent. |
| 4002 | Authentication failed: invalid or inactive key, no `tts_ws` access, IP not allowed, or no credits. |
| 4290 | Another text to speech stream of this account is already open. |

After an unexpected disconnect, wait about 15 seconds before reconnecting so the previous stream's lock has cleared.

## Credits

Streaming has its own rate per character (see [Pricing](../pricing/index.md)). Each text chunk is charged when it is received:

`credits = characters x (streaming rate + voice fee) x multiplier`, rounded up.

The multiplier follows the mode or engine, as for the REST endpoint, and `fast_mode` 1 or 2 uses the `emotion` multiplier. Credits for text that produced no audio because generation failed are put into a refund request automatically.

## Example

```python
# pip install websockets
import asyncio
import json
import websockets

API_KEY = "YOUR_API_KEY"
URL = "wss://moknah.io/api/v1/tts/ws/"


async def stream_tts():
    headers = {"Authorization": f"Bearer {API_KEY}"}
    async with websockets.connect(URL, additional_headers=headers) as ws:
        await ws.send(json.dumps({
            "type": "init",
            "voice_id": 1710,
            "output_format": "mp3_44100_128",
        }))
        print("Server:", await ws.recv())

        async def receive_audio():
            with open("audio.mp3", "wb") as f:
                async for message in ws:
                    if isinstance(message, bytes):
                        f.write(message)
                        continue
                    data = json.loads(message)
                    if data.get("type") == "end_of_stream":
                        break
                    if data.get("error"):
                        print("Error:", data["error"])

        receiver = asyncio.create_task(receive_audio())
        for chunk in ["مرحبا بكم.", "في منصة مكنة."]:
            await ws.send(json.dumps({"type": "text", "data": chunk}))
        await ws.send(json.dumps({"type": "stop"}))
        await receiver


asyncio.run(stream_tts())
```

```javascript
// npm install ws
const WebSocket = require("ws");
const fs = require("fs");

const ws = new WebSocket("wss://moknah.io/api/v1/tts/ws/", {
  headers: { Authorization: "Bearer YOUR_API_KEY" },
});
const file = fs.createWriteStream("audio.mp3");

ws.on("open", () => {
  ws.send(JSON.stringify({ type: "init", voice_id: 1710, output_format: "mp3_44100_128" }));
});

ws.on("message", (data, isBinary) => {
  if (isBinary) return file.write(data);
  const message = JSON.parse(data.toString());
  if (message.status === "ready") {
    ws.send(JSON.stringify({ type: "text", data: "مرحبا بكم." }));
    ws.send(JSON.stringify({ type: "stop" }));
  } else if (message.type === "end_of_stream") {
    ws.close();
  } else if (message.error) {
    console.error(message.error);
  }
});
```

Voice id 1710 is an example. Use an id from your own voice list.
