# Generate speech (REST)

> POST /api/v1/tts/generate/ converts up to 1,500 characters of text to an audio file. Parameters, voice settings, modes, output formats, credits and errors.

## Endpoint

`POST https://moknah.io/api/v1/tts/generate/`

Converts text to speech and returns the audio file in the response body. The call is synchronous: the response arrives when the audio is ready.

Requirements: an API key whose allowed services include `tts`, and a voice of the key's voice type.

## Request body

JSON.

| Field | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `text` | string | yes | | 1 to 1,500 characters. Control characters are replaced by spaces and repeated whitespace is collapsed before generation. |
| `voice_id` | integer or numeric string | yes | | A voice id from [List voices](voices.md). The voice must be available to the account and match the key's voice type. |
| `output_format` | string | no | `mp3_44100_128` | Audio format, see [Output formats](#output-formats). `null` uses the default. |
| `prerecording` | integer or string | no | `1` | Text processing mode: `1` Basic, `2` Arabic Tashkeel, `3` AI Poet. `2` and `3` are for Arabic only. |
| `language` | string | no | | Content language as an ISO 639-1 code (`ar`, `en`; `ar-JO` is accepted). It decides which `prerecording` modes are allowed and is not sent to the voice. |
| `voice_settings` | object | no | `{}` | See [Voice settings](#voice-settings). |

### Language and prerecording rules

- `prerecording` `2` or `3` with a `language` other than Arabic returns `400 INVALID_REQUEST`, with the reason under `details.language`.
- If `language` is omitted, `2` and `3` imply Arabic.
- An unknown language code returns `400 INVALID_REQUEST`.

## Voice settings

Unknown keys are rejected with `400 INVALID_REQUEST`.

### Standard engine voices

| Key | Type | Allowed values | Description |
| --- | --- | --- | --- |
| `mode` | string | `emotion`, `quality`, `studio` | The mode. A request without `mode` runs in `emotion`. |
| `temperature` | number | 0 to 100 | Variability. Lower is steadier and more predictable, higher is more varied and expressive. |
| `voice_similarity` | number | 0 to 100 | How closely the result follows the original voice. |
| `speed` | number | 0.7 to 1.2 | Speaking rate. Applies in `studio` mode only. |
| `enable_emotions` | boolean | | Deprecated. Accepted for compatibility; `mode` decides the behaviour. When `true`, `speed` and `fast_mode` must not be sent. |
| `fast_mode` | integer | 0, 1, 2 | Deprecated. Accepted for compatibility and has no effect on this endpoint. |

Modes:

| `mode` | Name | Best for |
| --- | --- | --- |
| `emotion` | Emotion and dialect (default) | Fast, expressive speech with emotions and dialects. Supports emotion tags. |
| `quality` | Quality emotion and dialect | Richer, more natural emotions and dialects. Takes a little longer. Supports emotion tags. |
| `studio` | Studio Quality | Clean, consistent narration with full voice controls. No emotion tags. |

In `emotion` and `quality`, `temperature` and `voice_similarity` are the controls. `speed` applies to `studio` only.

### Advanced engine voices

Available only when the Advanced engine is enabled and the key's voice type is `advanced`.

| Key | Type | Allowed values | Description |
| --- | --- | --- | --- |
| `context` | string | up to 500 characters | The strongest control. Describe accent, feeling, mood or purpose. |
| `setting` | string | up to 500 characters | Scene and mood. |
| `style` | string | `neutral`, `warm`, `energetic`, `serious`, `cheerful`, `poetic` | Overall delivery style. |
| `pace` | string | `slow`, `normal`, `fast` | Speaking pace. |

Advanced engine voices ignore `mode` and the Standard engine controls.

## Text markup

- Pause: `[break_X]` where X is seconds from 0.1 to 10, for example `Hello. [break_1.5] Now listen.` At most 20 breaks and 30 seconds of pause per text; extra ones are ignored.
- Emotion and sound tags in `emotion` and `quality` modes, in square brackets and in English whatever the text language: for example `[happy]`, `[sad]`, `[angry]`, `[calm]`, `[excited]`, `[whispering]`, `[shouting]`, `[laughing]`, `[sighs]`.
- Tags are still under testing and do not work every time. Check the result of a tagged line.

## Output formats

- MP3: `mp3_22050_32`, `mp3_24000_48`, `mp3_44100_32`, `mp3_44100_64`, `mp3_44100_96`, `mp3_44100_128`, `mp3_44100_192`
- PCM (raw 16-bit little-endian mono, no header): `pcm_8000`, `pcm_16000`, `pcm_22050`, `pcm_24000`, `pcm_32000`, `pcm_44100`, `pcm_48000`
- Opus (Ogg container): `opus_48000_32`, `opus_48000_64`, `opus_48000_96`, `opus_48000_128`, `opus_48000_192`
- WAV (16-bit mono, REST only): `wav_16000`, `wav_22050`, `wav_24000`, `wav_44100`, `wav_48000`

Default for REST: `mp3_44100_128`. Default for streaming: `pcm_24000`.

Format names read `codec_sampleRate_bitrate`. `pcm_*` is raw 16-bit little-endian mono audio with no header. `wav_*` is the same audio with a WAV header.

## Response

`200` with the binary audio.

| Header | Value |
| --- | --- |
| `Content-Type` | `audio/mpeg` for `mp3_*`, `audio/ogg` for `opus_*`, `audio/wav` for `wav_*`, `audio/pcm;rate=N;channels=1` for `pcm_*` |
| `Content-Disposition` | `attachment` with a generated file name |

A successful response carries no rate limit headers. They are sent with `402` and `429` responses; see [Limits](../limits/index.md).

If a text was flagged for review by the content check, the audio is still returned and the response carries an extra notice header.

## Credits

Credits are taken before generation:

`credits = characters x (rate of the prerecording mode + voice fee) x mode multiplier`, rounded up.

- `characters` is the length of `text` after cleaning.
- The rate per character for each `prerecording` mode is in [Pricing](../pricing/index.md).
- The mode multiplier depends on `mode` (Standard engine) or on the engine (Advanced):

| Voice engine and mode | Credit multiplier |
| --- | --- |
| Standard engine, `emotion` mode (default) | x1 |
| Standard engine, `quality` mode | x2 |
| Standard engine, `studio` mode | x2 |
| Advanced engine voices | x1.5 |

If generation fails after the charge, a refund request is created automatically and reviewed by the Moknah team.

## Concurrency

One text to speech REST request runs at a time per account. A second request sent while the first is still running returns `429 CONCURRENT_REQUEST`. Send requests one after another.

## Examples

```bash
curl -X POST "https://moknah.io/api/v1/tts/generate/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "مرحبا بك في منصة مكنة",
    "voice_id": 1328,
    "prerecording": 1,
    "language": "ar",
    "output_format": "mp3_44100_128",
    "voice_settings": {"mode": "emotion", "temperature": 25}
  }' \
  --output speech.mp3
```

```python
import requests

response = requests.post(
    "https://moknah.io/api/v1/tts/generate/",
    headers={"Authorization": "Bearer YOUR_API_KEY"},
    json={
        "text": "مرحبا بك في منصة مكنة",
        "voice_id": 1328,
        "prerecording": 2,
        "language": "ar",
        "voice_settings": {"mode": "studio", "speed": 1.0},
    },
    timeout=120,
)
if response.status_code == 200:
    with open("speech.mp3", "wb") as f:
        f.write(response.content)
else:
    print(response.status_code, response.json())
```

```javascript
const response = await fetch("https://moknah.io/api/v1/tts/generate/", {
  method: "POST",
  headers: {
    Authorization: "Bearer YOUR_API_KEY",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    text: "Welcome to Moknah.",
    voice_id: 1328,
    language: "en",
    voice_settings: { mode: "quality" },
  }),
});
if (response.ok) {
  const audio = await response.blob();
} else {
  console.error(await response.json());
}
```

## Errors

| Status | Code | When |
| --- | --- | --- |
| 400 | `INVALID_REQUEST` | A field is missing or invalid. `details` holds the reason per field. |
| 401 | `authentication_failed` | Missing, invalid or inactive key, or a caller outside the key's IP allowlist. |
| 402 | `INSUFFICIENT_CREDITS` | The account balance is too low. `details` has `credits_remaining` and `credits_used`. |
| 402 | `CREDIT_LIMIT_EXCEEDED` | The key's own credit limit would be exceeded. |
| 403 | (flat `detail`) | The key's allowed services do not include `tts`. |
| 422 | `CONTENT_REJECTED` | The text was refused by the content policy check. |
| 429 | `CONCURRENT_REQUEST` | Another text to speech request of the account is still running. |
| 429 | `RATE_LIMIT_EXCEEDED` | Requests per minute or credits per minute exceeded. `Retry-After` says how long to wait. |
| 500 | `INTERNAL_SERVER_ERROR` or a generation error code | Generation failed. `details.request_id` identifies the request for support. |

Each code is explained in [Errors](../errors/index.md).
