# Integrate text to speech

> Add Moknah text to speech to an application through the REST API, from key creation to production error handling, with the check that confirms each step.

## Steps

| Step | Do | Check |
| --- | --- | --- |
| 1. Get a key | Dashboard, **API**, **Manage API Keys**, **New Key**. Allow the `tts` service (and `tts_ws` for streaming). | `GET /api/v1/key/info/` returns the key with `status` `active`. |
| 2. Pick a voice | `POST /api/v1/voices/`. Choose by `voice_badges` and listen to `voice_sample_url`. | You hold a `voice_id` that came from the response. |
| 3. Generate | `POST /api/v1/tts/generate/` with `text`, `voice_id` and, for Arabic, `language`. | Status `200` and a `Content-Type` starting with `audio/`. |
| 4. Handle errors | Branch on the status code, below. | Each error path is exercised once. |
| 5. Respect limits | Send one request at a time and stay under the per-minute limits. | No `429` responses in normal operation. |

## Choosing the endpoint

- A complete file per request: [Generate speech (REST)](../api/tts-generate.md).
- Audio that starts playing while the text is still arriving, such as LLM output: [Stream speech (WebSocket)](../api/tts-stream.md).

## Text longer than the limit

The REST endpoint takes up to 1,500 characters per request. For longer text:

1. Split at sentence boundaries into parts under the limit.
2. Send the parts one after another, never in parallel.
3. Join the audio in order. With `pcm_*` or `wav_*` output the parts concatenate cleanly; MP3 parts can be joined with an audio tool.

For whole books, Audio Studio does the splitting, voicing, review and merging; an assistant can drive it through [MCP](../mcp/overview.md).

## A production client

```python
import time
import requests

API = "https://moknah.io/api/v1"


class MoknahTTS:
    def __init__(self, api_key):
        self.session = requests.Session()
        self.session.headers["Authorization"] = f"Bearer {api_key}"

    def speak(self, text, voice_id, language=None, max_attempts=5, **settings):
        body = {"text": text, "voice_id": voice_id}
        if language:
            body["language"] = language
        if settings:
            body["voice_settings"] = settings
        for attempt in range(max_attempts):
            response = self.session.post(f"{API}/tts/generate/", json=body, timeout=180)
            if response.status_code == 200:
                return response.content
            if response.status_code == 429:
                wait = int(response.headers.get("Retry-After", 0)) or 2 ** attempt
                time.sleep(wait)
                continue
            if response.status_code >= 500:
                time.sleep(2 ** attempt)
                continue
            raise RuntimeError(f"{response.status_code}: {response.text}")
        raise RuntimeError("Gave up after repeated 429 or 5xx responses")


tts = MoknahTTS("YOUR_API_KEY")
audio = tts.speak("مرحبا بك في منصة مكنة", voice_id=1328, language="ar", mode="emotion")
with open("speech.mp3", "wb") as f:
    f.write(audio)
```

Call `speak` from one worker at a time per account, for example behind a queue.

## Error handling

| Status | Meaning | What to do |
| --- | --- | --- |
| 400 | Invalid field | Fix the request. `error.details` names the field. Do not retry unchanged. |
| 401 | Key problem | Check the key, its status, and the IP allowlist. Do not retry. |
| 402 | Not enough credits, or the key's credit cap is reached | Top up or raise the cap. Do not retry until then. |
| 403 | The key may not use this service | Allow the service on the key. |
| 422 | Text refused by the content check | Do not retry the same text. |
| 429 | Another request is running, or a per-minute limit is reached | Wait (`Retry-After` when present, otherwise back off) and retry. |
| 500 | Generation failed | Retry with backoff. If it persists, send `error.details.request_id` to support. |

Details of each code are in [Errors](../errors/index.md).

## Cost control

- Estimate before sending: characters multiplied by the current rate and multiplier in [Pricing](../pricing/index.md).
- `quality` and `studio` modes, Arabic Tashkeel, AI Poet and voices with a fee cost more than the basic case.
- Give each integration its own key with a credit limit, so a bug cannot spend the whole balance.

## Security

Keep the key on your server. Do not ship it in a web page or a mobile app; proxy the request through your backend.
