# Gemini Text-to-Speech (TTS)

Synthesize speech from text using `gemini-3.8-flash-tts` over the native Gemini endpoint. Requests return audio synchronously—there is no task ID or polling.

> Model availability is determined by the live `GET /v1/models` response for your API key. Do not submit synthesis requests if the model does not appear in that list.

## Endpoint & Authentication

```http
POST https://vip.brioi.com/v1beta/models/gemini-3.8-flash-tts:generateContent
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

Authenticate with your Brioi API key via `Authorization: Bearer`, `x-goog-api-key`, or the `?key=` query parameter. Only the native Gemini `generateContent` format is supported; OpenAI formats (`/v1/chat/completions`, `/v1/audio/speech`) are not available.

> This endpoint extends the native Gemini payload with a part-level `speech_metadata` object for vocal style and speaker assignment. Official Google SDKs do not generate `speech_metadata` automatically, so include it manually in your JSON payload. Multi-speaker dialogue requires `speech_metadata.speaker` on every part—prefixing speaker names inside `text` (such as `"Alex: ..."`) cannot substitute for it.

## Billing

Billed per request: each successful call counts as one request regardless of text length or audio duration. Failed requests are not charged. Submitting one line of dialogue per request is recommended.

## Request Schema

| Field | Type | Required | Description |
|---|---|---:|---|
| `contents` | array | Yes | Must contain a single content item. |
| `contents[].role` | string | No | Set to `user`. |
| `contents[].parts[].text` | string | Yes | Text to speak aloud. Use one `text` part for single-speaker synthesis, or one part per line for multi-speaker dialogue. |
| `contents[].parts[].speech_metadata.style` | string | No | Vocal delivery prompt, e.g. `"tearful"` or `"low, restrained tone"`. Affects delivery only and is not spoken aloud. |
| `contents[].parts[].speech_metadata.speaker` | string | Conditional | Required for multi-speaker dialogue. Speaker identifier for this line; must match a `speaker` entry in `multiSpeakerVoiceConfig`. |
| `generationConfig.responseModalities` | string[] | Yes | Must be `["AUDIO"]`. |
| `generationConfig.speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName` | string | Conditional | Required for single-speaker synthesis. Voice name from the list below; mutually exclusive with `multiSpeakerVoiceConfig`. |
| `generationConfig.speechConfig.multiSpeakerVoiceConfig.speakerVoiceConfigs` | array | Conditional | Required for multi-speaker dialogue. One entry per speaker with `speaker` and `voiceConfig.prebuiltVoiceConfig.voiceName`; mutually exclusive with `voiceConfig`. |

## Prebuilt Voices

30 built-in voices are supported (voice cloning is not supported). Voices are language-independent—the same voice can speak English, Chinese, Japanese, Korean, and more.

`Zephyr`, `Puck`, `Charon`, `Kore`, `Fenrir`, `Leda`, `Orus`, `Aoede`, `Callirrhoe`, `Autonoe`, `Enceladus`, `Iapetus`, `Umbriel`, `Algieba`, `Despina`, `Erinome`, `Algenib`, `Rasalgethi`, `Laomedeia`, `Achernar`, `Alnilam`, `Schedar`, `Gacrux`, `Pulcherrima`, `Achird`, `Zubenelgenubi`, `Vindemiatrix`, `Sadachbia`, `Sadaltager`, `Sulafat`

## Single-Speaker Example

```bash
curl -X POST "https://vip.brioi.com/v1beta/models/gemini-3.8-flash-tts:generateContent" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "Just go... I never want to see your face again.",
        "speech_metadata": {"style": "Tearful, voice trembling on the second half"}
      }]
    }],
    "generationConfig": {
      "responseModalities": ["AUDIO"],
      "speechConfig": {
        "voiceConfig": {
          "prebuiltVoiceConfig": {"voiceName": "Leda"}
        }
      }
    }
  }'
```

## Multi-Speaker Dialogue Example

Synthesize an entire dialogue exchange in a single request (still billed as one call): place each spoken turn in its own part with `speech_metadata.speaker`, and assign each speaker a voice in `multiSpeakerVoiceConfig`.

```bash
curl -X POST "https://vip.brioi.com/v1beta/models/gemini-3.8-flash-tts:generateContent" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [
        {"text": "Have you been lying to me for the past three years?", "speech_metadata": {"speaker": "Alex", "style": "Low voice, restrained tone"}},
        {"text": "I have not... please let me explain.", "speech_metadata": {"speaker": "Maya", "style": "Tearful"}}
      ]
    }],
    "generationConfig": {
      "responseModalities": ["AUDIO"],
      "speechConfig": {
        "multiSpeakerVoiceConfig": {
          "speakerVoiceConfigs": [
            {"speaker": "Alex", "voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Charon"}}},
            {"speaker": "Maya", "voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Leda"}}}
          ]
        }
      }
    }
  }'
```

The response contains a single continuous audio clip for the full exchange rather than separate per-line files. When you need line-by-line timeline alignment (for example, dubbing over video), submit one line per request.

## Response & Audio Conversion

```json
{
  "candidates": [{
    "content": {
      "role": "model",
      "parts": [{
        "inlineData": {
          "mimeType": "audio/l16; rate=24000; channels=1",
          "data": "BASE64_PCM_DATA"
        }
      }]
    },
    "finishReason": "STOP"
  }],
  "usageMetadata": {"promptTokenCount": 12, "candidatesTokenCount": 78, "totalTokenCount": 90},
  "modelVersion": "gemini-3.8-flash-tts"
}
```

`inlineData.data` is base64-encoded raw PCM (`24000` Hz, mono, 16-bit signed little-endian) with no WAV header, so it cannot be played directly as `.wav` or `.mp3`. Convert it using either approach below:

Convert to WAV in Python:

```python
import base64, wave

def save_wav(resp: dict, path: str) -> None:
    parts = resp["candidates"][0]["content"]["parts"]
    pcm = b"".join(base64.b64decode(p["inlineData"]["data"]) for p in parts if "inlineData" in p)
    with wave.open(path, "wb") as w:
        w.setnchannels(1)
        w.setsampwidth(2)
        w.setframerate(24000)
        w.writeframes(pcm)
```

Convert decoded raw PCM to MP3 with `ffmpeg`:

```bash
ffmpeg -f s16le -ar 24000 -ac 1 -i speech.pcm speech.mp3
```

## Limits & Error Handling

- When `multiSpeakerVoiceConfig` is used, every text part must include `speech_metadata.speaker`; otherwise the API returns `400`.
- Put delivery cues in `speech_metadata.style`, not inside `text`—cues placed inside `text` may be read aloud.
- Synchronous synthesis blocks until generation completes (typically a few seconds up to ~20 seconds). If a client times out, do not blindly resubmit; record the `X-Oneapi-Request-Id` response header and error details first.
- HTTP status codes: `400` invalid parameters, `401` missing or invalid API key, `403` insufficient balance/quota or missing model permission, `429` rate limit exceeded, `503` service temporarily unavailable, `500` / `502` transient server error.

