POST /v1/audio/speech
GET /v1/audio/voices
POST /v1/audio/voices
DELETE /v1/audio/voices/{voice_id}
Single OpenAI-compatible endpoint for TTS. The Gemini models supported here
are gemini-3.8-flash-tts, gemini-3.8-flash-lite-tts,
gemini-3.1-flash-tts-preview and gemini-2.5-flash-preview-tts. The request
surface is intentionally small:
required model and input, plus optional voice, instructions and
response_format.
Omitting model fails request validation with HTTP 422; the gateway does
not silently substitute a Gemini TTS model.
For Gemini TTS models, omitting response_format returns a full WAV body
(audio/wav, 24 kHz mono PCM-16). Ask for another container with
response_format: mp3, opus, aac, flac, wav or pcm (raw 16-bit
24 kHz mono); the Content-Type matches what you receive. ElevenLabs models
return MP3 (audio/mpeg) by default.
Gemini TTS quick reference
| Field | Values |
|---|---|
model |
gemini-3.1-flash-tts-preview, gemini-3.8-flash-tts, gemini-3.8-flash-lite-tts, gemini-2.5-flash-preview-tts |
voice |
Any of the 30 Gemini voices below (for example Aoede, Charon, Fenrir, Kore, Leda, Orus, Puck, Zephyr), the additional voice Orbit, or an OpenAI voice name: alloy, echo, fable, onyx, nova, shimmer. Default Zephyr. |
instructions |
Optional style / director's notes, up to 4,000 characters, e.g. "Warm, unhurried audiobook narrator". Honoured with the voices Aoede, Charon, Fenrir, Kore, Leda, Orbit, Orus, Puck, Zephyr and the OpenAI voice names; with other voices put the style into input as a prefix (see "Style control"). |
response_format |
mp3, opus, aac, flac, wav (default), pcm |
input |
Text to speak. Long text is accepted: the gateway splits it at sentence boundaries, synthesises the parts and returns one continuous file. |
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-o narration.mp3 \
-d '{
"model": "gemini-3.1-flash-tts-preview",
"voice": "Charon",
"instructions": "Calm documentary narrator, slightly slow, warm tone",
"response_format": "mp3",
"input": "Deep in the forest, the first light of morning reached the old oak."
}'
from openai import OpenAI
client = OpenAI(base_url="https://gateway.api429.com/v1", api_key="YOUR_API_KEY")
with client.audio.speech.with_streaming_response.create(
model="gemini-3.1-flash-tts-preview",
voice="nova", # OpenAI voice names are accepted
instructions="Cheerful, energetic product announcement",
response_format="mp3",
input="Meet the new version of our app: faster, simpler and free to try.",
) as response:
response.stream_to_file("announcement.mp3")
TTS surface support matrix
| Surface | Route / API | Supported controls | Output / caveats |
|---|---|---|---|
| OpenAI-compatible gateway | POST /v1/audio/speech |
model, input, voice, instructions, response_format, delivery |
Full-body response. Gemini returns WAV unless response_format asks for mp3 / opus / aac / flac / pcm; ElevenLabs returns MP3. No temperature, languageCode, first-class multi-speaker, streaming, or Cloud audioConfig passthrough. |
| Voices | GET / POST / DELETE /v1/audio/voices |
Catalogue lookup (language, q, limit, offset), cloning from an uploaded sample, scope=mine |
Fish models only. A cloned voice is private to the key that created it. |
| Gemini-native gateway | POST /gemini/v1beta/models/{model}:generateContent |
responseModalities: ["AUDIO"], speechConfig.voiceConfig, multiSpeakerVoiceConfig, languageCode, temperature |
Non-streaming through this balancer. Response is Gemini JSON with base64 raw PCM; wrap into WAV client-side. |
| Cloud Text-to-Speech direct | Google Cloud text:synthesize / text:streamingSynthesize |
prompt + text, audioEncoding, sampleRateHertz, speed, volume gain, MultiSpeakerMarkup, streaming, advancedVoiceOptions.safetySettings |
Use Google Cloud auth directly. These controls are not proxied by /v1/audio/speech. |
Available models
| Model | Status | Text in / 1M | Audio out / 1M tokens | Derived base / 1K chars | API429 / 1K chars* | Output |
|---|---|---|---|---|---|---|
gemini-3.8-flash-tts |
Newest Gemini TTS, most natural delivery | $0.50† | $9† | $0.0167 | $0.0050 | audio/wav |
gemini-3.8-flash-lite-tts |
Cheapest Gemini TTS, low latency | $0.50† | $6† | $0.0111 | $0.0033 | audio/wav |
gemini-3.1-flash-tts-preview |
Expressive, supports audio tags | $1.00 | $20 | $0.0370 | $0.0111 | audio/wav |
gemini-2.5-flash-preview-tts |
Previous generation, Flash | $0.50 | $10 | $0.0185 | $0.0056 | audio/wav |
† Google's promotional price through 2026-12-31; from 2027-01-01 Google lists
gemini-3.8-flash-ttsat $1.00 / $18 andgemini-3.8-flash-lite-ttsat $1.00 / $12 per 1M tokens.
Google API surface matters.
gemini-2.5-flash-ttsis a model ID for Google's separate Cloud Text-to-Speech API. It is not valid on GeminigenerateContent, and API429 does not currently proxy Cloud TTStext:synthesizeortext:streamingSynthesize. A400 INVALID_ARGUMENTfromgenerateContentfor that ID is an endpoint/model mismatch, not a missing Cloud API switch on the API429 gateway.
Cartesia Sonic
Send text to POST /v1/audio/speech with one of the following model IDs. Use a voice ID from GET /v1/audio/voices?model=cartesia-sonic-3.6 (replace the model with your selected version).
ElevenLabs models
| Model | Best for | API429 per 1,000 characters | Output |
|---|---|---|---|
elevenlabs-gen |
Expressive ElevenLabs speech and character voices, 70+ languages | Current rate | audio/mpeg |
eleven_v4 |
Newest ElevenLabs model: most expressive delivery, 90+ languages, IPA pronunciation control | Current rate | audio/mpeg |
eleven_v4_turbo |
Eleven v4 quality with lower latency, for live and conversational use | Current rate | audio/mpeg |
For elevenlabs-gen, pass the native
ElevenLabs voice ID in the standard OpenAI-compatible voice field; if you
omit it or pass an unrecognized name, a default voice is used.
Requests are billed at the elevenlabs-gen rate above. Long input is
chunked and returned as a single joined MP3.
The legacy ids eleven_v3, eleven_multilingual_v2, eleven_flash_v2_5
and api429-tts remain accepted for backward compatibility but are no
longer listed in GET /v1/models; new integrations should use
elevenlabs-gen.
Eleven v4 and v4 Turbo
eleven_v4 and eleven_v4_turbo are ElevenLabs' newest speech models
(released 2026-09-28): more expressive delivery, 90+ languages and phonetic
(IPA) pronunciation control. v4 Turbo trades a little quality for lower
latency. Both are listed in GET /v1/models; request them by exact id on
POST /v1/audio/speech. Prices are in the table above. Voices work as for
elevenlabs-gen: pass a native ElevenLabs voice ID in voice, or omit it
for the default voice. Output is MP3 (audio/mpeg).
If the service is unavailable, a v4 request fails. eleven_v3 remains
available; pick the model explicitly in each request.
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "eleven_v4",
"voice": "hpp4J3VqNfWAUOO0d1Us",
"input": "Hello! This is Eleven v4 through API429."
}' \
--output speech.mp3
If the speech provider's content filter blocks part of your text, the
request returns 422 naming how many fragments were rejected; rephrase
the flagged wording and retry.
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "elevenlabs-gen",
"voice": "hpp4J3VqNfWAUOO0d1Us",
"input": "Привет! Это озвучка ElevenLabs через API429."
}' \
--output speech.mp3
Fish Audio model
| Model | Best for | Official / 1M UTF-8 bytes | API429 / 1M UTF-8 bytes* | Output |
|---|---|---|---|---|
fish-s2.1-pro |
Long-form narration, 80+ languages, large public voice library | $15.00 | $4.50 | audio/mpeg |
* The API429 column shows the standard 70% client discount. A per-client billing profile may override the discount shown here.
Fish Audio bills the UTF-8 byte length of the input text, and so do we: 1 byte per Latin character, 2 per Cyrillic, 3 per Chinese, Japanese or Korean character. 1,000 Russian characters therefore cost the same as 2,000 English ones ($0.03 official, $0.009 after the standard discount).
voice is required for this model. Pass the 32-character hex id of a
voice from the catalogue (see below), or the id of a voice you cloned. There
is no default: omitting voice, sending an empty string, or sending a voice
name such as "Sarah" all return 400 with the id format spelled out. That
is deliberate. A substituted default produced perfectly good audio in the
wrong voice and answered 200, so a typo looked like the gateway ignoring
voice altogether — one client spent a day on exactly that. Voices carry
their own language tags, and many are multilingual, so one voice often covers
several markets.
An id that has the right shape but does not exist is currently reported as
502("could not be served by any configured provider") rather than a4xx, because the provider's rejection is relayed as an upstream failure. If you get a502from/v1/audio/speech, check the voice id against the catalogue before reporting an outage.
Output format. fish-s2.1-pro honours response_format: mp3 (default),
wav, pcm and opus. Use wav when the consumer requires RIFF/WAVE — some
post-processing pipelines reject MP3. WAV is roughly six times larger than the
same audio as MP3, so prefer mp3 unless you specifically need RIFF.
Long input is handled for you. Text longer than a few thousand characters
is split on sentence boundaries, synthesised in parallel and returned as a
single joined clip — never an archive, and never a word cut in half. An hour of
narration (~60 000 characters) takes roughly three minutes end to end. opus
is the one exception: it cannot be joined safely, so long input in that format
returns 400 — use mp3, wav or pcm instead.
Billing note. The provider meters UTF-8 bytes, while the rate above is per character. Latin text is one byte per character, but Cyrillic is two and CJK three, so non-Latin narration costs proportionally more upstream than the per-character figure suggests. Always use the authoritative bill in
/api/client/usage/dailyfor budgeting.
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "fish-s2.1-pro",
"input": "Привет! Это озвучка Fish Audio через API429.",
"voice": "90e65eaaf50e4470b8e6d43ee6afd7d5",
"response_format": "wav"
}' \
--output speech.wav
Voice catalogue
GET /v1/audio/voices
Since voice is required and a wrong one is a 400, this is how you find a
valid id. Over a thousand public voices are available, in many languages.
| Parameter | Default | Meaning |
|---|---|---|
model |
fish-s2.1-pro |
Which model's catalogue to list. Models without one answer 400. |
language |
— | Keep voices tagged with this language. Most voices are multilingual, so a voice usually appears under several. |
q |
— | Substring match on the voice name, case-insensitive. |
limit / offset |
100 / 0 |
Page window; limit is capped at 1000. |
scope |
catalogue |
mine lists your own cloned voices instead (see below). |
curl "https://gateway.api429.com/v1/audio/voices?language=ru&q=narrator&limit=5" \
-H "Authorization: Bearer YOUR_API_KEY"
{
"object": "list",
"model": "fish-s2.1-pro",
"total": 37,
"offset": 0,
"data": [
{
"id": "90e65eaaf50e4470b8e6d43ee6afd7d5",
"name": "Documentary narrator",
"languages": ["ru", "en"],
"tags": ["narration", "calm"],
"description": "Warm, unhurried delivery…",
"author": "…",
"popularity": 48213
}
]
}
Take id from any entry and pass it as voice on POST /v1/audio/speech.
Results are ordered by popularity — how many jobs the voice has served — so
the first page is a reasonable shortlist rather than an arbitrary slice.
total counts everything matching the filter, not the page. Only public,
finished voices appear.
Cloned voices
POST /v1/audio/voices
GET /v1/audio/voices?scope=mine
DELETE /v1/audio/voices/{voice_id}
Upload a recording of a voice once and synthesise with it from then on. The
returned id behaves like any catalogue voice — pass it in voice — except
that it is private to the API key that created it.
Send the audio as multipart/form-data:
| Field | Required | Meaning |
|---|---|---|
file |
yes | The voice sample. WAV, MP3, FLAC, OGG/Opus or M4A. Ten to thirty seconds of clear speech with little background noise gives the best result; more audio does not help. |
name |
yes | Your own label for the voice. |
transcript |
no | Exactly what is said in the sample. The clone works without it and matches the original more closely with it. |
curl https://gateway.api429.com/v1/audio/voices \
-H "Authorization: Bearer YOUR_API_KEY" \
-F "file=@narrator.mp3" \
-F "name=House narrator" \
-F "transcript=I have been recording audiobooks for eleven years."
{
"id": "voice_b3b86385ec1b489f9d16183f603ee25c",
"object": "audio.voice",
"name": "House narrator",
"created": 1789661983,
"sample_bytes": 197431,
"sample_format": "audio/mpeg",
"has_transcript": true
}
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "fish-s2.1-pro",
"input": "This text is read in the cloned voice.",
"voice": "voice_b3b86385ec1b489f9d16183f603ee25c"
}' \
--output cloned.mp3
A cloned voice works everywhere a catalogue voice does, long-form splitting included: every chunk of a long narration is produced in the same voice.
Your voices are yours. A cloned voice is bound to the API key that created
it. Another key using the id gets 404, the same answer as an id that never
existed, and cannot see it in its own scope=mine listing. DELETE removes
the voice and the stored recording; afterwards the id answers 404.
Limits and errors.
| Situation | Response |
|---|---|
| File is not recognisable audio | 400 |
| Sample larger than 8 MB | 413 — ten to thirty seconds is plenty, and MP3 is far smaller than WAV |
| 25 voices already registered | 409 — delete one first |
| Cloned voice used with a model that has no cloning | 400 |
| Cloning not enabled for the deployment | 503 |
Cloned synthesis is billed exactly like any other synthesis on the model —
per character of input, at the same rate. Registering, listing and deleting
a voice are free.
Getting a link instead of a file
An hour of narration is about 10 MB as MP3 and far more as WAV, which is
awkward to carry in a synchronous response body. Set "delivery": "url" and
the clip is uploaded to our CDN and described by a small JSON body instead:
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "fish-s2.1-pro",
"input": "…длинный текст ролика…",
"delivery": "url"
}'
{
"url": "https://api429.lon1.cdn.digitaloceanspaces.com/api429/tts/…mp3",
"mime": "audio/mpeg",
"bytes": 10452992
}
Omit delivery (or send "inline") and you get the raw audio bytes exactly as
before — the default is unchanged.
gemini-3.1-flash-tts-preview currently has a documented 8,192 input-token
limit and 16,384 output-token limit. Upstream Batch API is supported for that
model, while caching, function calling, Live API, structured output, code
execution, grounding, and URL context are not.
* How we derive the effective rate. Google bills TTS per audio token: 1 second of output = 25 audio tokens. English speech averages 13.5 chars/sec, so 1M audio tokens ≈ 40 000 s ≈ 540 000 chars.
$20 / 1M audio tokens × (1M / 540K) = $0.03704 per 1K chars (Gemini 3.1) $0.0370 rounded base rate × 30% after the standard 70% discount = $0.0111 billedRussian / CJK speech is slower (~10–12 chars/sec) → our per-char rate slightly under-bills non-English traffic (error <25%). For budget planning always use the authoritative bill reported by
/api/client/usage/daily— it reflects the actual Google charge, not this estimate.Text input ($1.00 / 1M text tokens) adds <5 % to the total for typical TTS requests, so clients can usually plan on just the audio-output rate.
Quick start (OpenAI-compatible)
from openai import OpenAI
client = OpenAI(
base_url="https://gateway.api429.com/v1",
api_key="YOUR_API_KEY",
)
response = client.audio.speech.create(
model="gemini-3.1-flash-tts-preview", # current Gemini TTS model
voice="Kore",
input="Hello, welcome to our API."
)
response.stream_to_file("output.wav")
curl https://gateway.api429.com/v1/audio/speech \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-o output.wav \
-d '{
"model": "gemini-3.1-flash-tts-preview",
"voice": "Kore",
"input": "Hello, welcome to our API."
}'
// Node.js / TypeScript via the official OpenAI SDK
import OpenAI from "openai";
import { writeFile } from "node:fs/promises";
const client = new OpenAI({
baseURL: "https://gateway.api429.com/v1",
apiKey: process.env.BALANCER_API_KEY!,
});
const speech = await client.audio.speech.create({
model: "gemini-3.1-flash-tts-preview",
voice: "Kore",
input: "Hello, welcome to our API.",
});
await writeFile("output.wav", Buffer.from(await speech.arrayBuffer()));
// Node.js / browser via plain fetch (no SDK dependency)
const res = await fetch("https://gateway.api429.com/v1/audio/speech", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.BALANCER_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gemini-3.1-flash-tts-preview",
voice: "Kore",
input: "Hello, welcome to our API.",
}),
});
if (!res.ok) {
const err = await res.json();
throw new Error(`TTS failed: ${err.error?.message ?? res.status}`);
}
const wav = Buffer.from(await res.arrayBuffer());
require("node:fs").writeFileSync("output.wav", wav);
OpenAI SDK example with expressive tags
Gemini 3.1 Flash TTS Preview adds expressive bracket tags for narrative control. Keep the tags in English even when the spoken text is Russian or another language.
response = client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Puck",
input=(
"Прочитай как тревожный рассказчик: "
"Я открыл дверь. [short pause] Там никого не было. [gasp]"
),
)
response.stream_to_file("tagged.wav")
response_formatfield. Gemini TTS returns the container you ask for:mp3,opus,aac,flac,wavorpcm(raw 16-bit 24 kHz mono, no header). Withoutresponse_formatyou get a 24 kHz mono PCM-16 WAV body. Save the file with the matching extension.
Voice library (30 prebuilt voices)
Gemini TTS ships with 30 distinct voices. Each carries a unique tonal character; pick one that matches your use case.
All previews speak the same English pangram ("The quick brown fox jumps over the lazy dog.") so you can A/B them by ear. Russian / CJK delivery sounds slightly different but maintains the same character.
Female voices (14):
| Voice | Character | Preview |
|---|---|---|
Achernar |
Soft | |
Aoede |
Breezy | |
Autonoe |
Bright | |
Callirrhoe |
Easy-going | |
Despina |
Smooth | |
Erinome |
Clear | |
Gacrux |
Mature | |
Kore ⭐ |
Firm | |
Laomedeia |
Upbeat | |
Leda |
Youthful | |
Pulcherrima |
Forward | |
Sulafat |
Warm | |
Vindemiatrix |
Gentle | |
Zephyr |
Bright |
Male voices (16):
| Voice | Character | Preview |
|---|---|---|
Achird |
Friendly | |
Algenib |
Gravelly | |
Algieba |
Smooth | |
Alnilam |
Firm | |
Charon |
Informative | |
Enceladus |
Breathy | |
Fenrir |
Excitable | |
Iapetus |
Clear | |
Orus |
Firm | |
Puck |
Upbeat | |
Rasalgethi |
Informative | |
Sadachbia |
Lively | |
Sadaltager |
Knowledgeable | |
Schedar |
Even | |
Umbriel |
Easy-going | |
Zubenelgenubi |
Casual |
⭐ Kore is the balancer default if voice is omitted or unknown.
Unknown voice names silently fall back to Kore — the balancer
whitelists names before forwarding to upstream.
Note for offline / GitHub readers. The previews above are hosted at
https://hostkey24760.api429.com/admin-panel/front-max/voice-samples/<Voice>.mp3— public, no auth required. If you're reading this on GitHub or in an offline mirror, pop the URLs into your browser to listen. Alternative: Google's interactive AI Studio Voice Library plays each voice with multiple sample phrases.
Voice picker by use-case
Quick guide to narrow 30 → 1 by what you're building. All recommendations are subjective — listen to the previews and trust your ears.
| Use-case | Recommended voices | Why |
|---|---|---|
| Audiobook narration (calm, sustained) | Sulafat, Charon, Rasalgethi, Vindemiatrix |
Warm, even, easy to listen to for hours |
| Podcast / talk-show host (energetic) | Puck, Zephyr, Laomedeia, Sadachbia |
Upbeat, engaging, expressive intonation |
| News / weather / formal | Kore, Charon, Algieba, Schedar |
Firm, neutral, "anchor"-like delivery |
| Voice assistant / chatbot | Kore, Orus, Aoede, Achird |
Friendly, balanced, doesn't fatigue |
| Children's content | Leda, Aoede, Achird |
Youthful, breezy, approachable |
| Suspense / dramatic narration | Enceladus, Algenib, Gacrux, Fenrir |
Breathy, gravelly, mature, excitable — can carry tension |
| Russian / CJK | Kore, Charon, Sulafat, Puck |
These four hold their character cleanest in non-English |
| Two-speaker dialogue | One bright (Puck/Zephyr/Aoede) + one firm (Kore/Charon) |
Maximum tonal contrast for clarity |
Languages
Gemini TTS auto-detects the language from the input text. 24 languages GA:
Arabic (Egypt), Bangla (Bangladesh), Dutch, English (India, US), French, German, Hindi, Indonesian, Italian, Japanese, Korean, Marathi, Polish, Portuguese (Brazil), Romanian, Russian, Spanish (Spain), Tamil, Telugu, Thai, Turkish, Ukrainian, Vietnamese.
50+ more in Preview (Chinese Mandarin, Greek, Hebrew, Norwegian, Swedish, Czech, and more — see Google's official list).
# Russian — just write the text, no extra parameter needed
response = client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Kore",
input="Привет, как твои дела сегодня?",
)
Style control
Two mechanisms can shape delivery:
1. Natural-language style prefix
Prepend a style instruction to the text.
client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Enceladus",
input="Say in a spooky whisper: Something wicked this way comes.",
)
client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Puck",
input="Read excitedly, like breaking news: The rocket has landed!",
)
2. Expressive audio tags
Square-bracket tags mid-sentence control non-speech sounds and pacing. Google does not publish an exhaustive taxonomy; treat the list below as official/common examples from Gemini API and Cloud TTS docs, then test the exact phrasing with your voice and language.
client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Puck",
input="That joke was amazing. [laughs] I cannot stop thinking about it. [short pause] But seriously…",
)
Common modes:
Non-speech sounds — vocal inserts:
| Tag | Effect |
|---|---|
[sigh] / [sighs] |
Exhale |
[laughs] / [laughing] / [giggles] |
Chuckle or laughter |
[gasp] |
Surprised inhale |
[uhm] |
Filler sound |
[cough] / [coughs] |
Cough |
[chuckling] |
Low laugh while speaking |
Style modifiers — change delivery characteristics:
| Tag | Effect |
|---|---|
[whispers] / [whispering] |
Lower volume, breathy |
[shouting] |
Higher energy, louder |
[sarcasm] / [sarcastically] |
Dry, deadpan delivery |
[robotic] |
Synthetic, flat affect |
[extremely fast] / [very fast] |
Accelerated pace |
[very slow] |
Slower delivery |
Vocalized markup — emotional colouring:
| Tag | Effect |
|---|---|
[amazed] |
Amazed tone |
[crying] |
Crying tone |
[excited] / [excitedly] |
Raised pitch and pace |
[scared] |
Trembling, higher pitch |
[curious] |
Questioning intonation |
[bored] |
Flat, drawn out |
[reluctantly] / [mischievously] |
Hesitant or playful tone |
[serious] / [tired] / [panicked] / [trembling] |
Mood modifiers |
Pacing — silence gaps:
| Tag | Effect |
|---|---|
[short pause] |
~250 ms silence |
[medium pause] |
~500 ms silence |
[long pause] |
~1 s silence |
Language note: keep audio tags in English regardless of the spoken language.
[laughs]works inside a Russian sentence;[смеётся]may be read aloud literally.
Temperature (creativity control)
Gemini TTS supports a temperature parameter in the range (0.0, 2.0].
Higher values give more expressive / varied reads; lower values stay
predictable. The OpenAI-compatible endpoint doesn't expose it yet — use
the Gemini-native non-streaming endpoint if you need it:
curl "https://gateway.api429.com/gemini/v1beta/models/gemini-3.1-flash-tts-preview:generateContent" \
-H "x-goog-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text": "Tell me about the stars"}]}],
"generationConfig": {
"responseModalities": ["AUDIO"],
"temperature": 1.5,
"speechConfig": {
"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Kore"}}
}
}
}'
The Gemini-native response contains base64 raw PCM in
candidates[0].content.parts[0].inlineData.data; decode it and wrap as
24 kHz mono PCM-16 WAV client-side.
Sane starting points:
- 0.2–0.5 — narration, consistent reads, audiobooks
- 0.8–1.2 — conversational, default feel
- 1.5–2.0 — theatrical, emotional, podcast hosts
Multi-speaker dialogue
Gemini TTS can voice a conversation between up to 2 speakers in a
single call. The balancer's OpenAI-compatible endpoint doesn't
expose speaker_voice_configs yet — use the Gemini-native
non-streaming endpoint for multi-speaker output:
curl "https://gateway.api429.com/gemini/v1beta/models/gemini-3.1-flash-tts-preview:generateContent" \
-H "x-goog-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"contents": [{"parts": [{"text":
"TTS the following conversation:\nJoe: How is it going today Jane?\nJane: Not too bad, how about you?"
}]}],
"generationConfig": {
"responseModalities": ["AUDIO"],
"speechConfig": {
"multiSpeakerVoiceConfig": {
"speakerVoiceConfigs": [
{"speaker": "Joe", "voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Kore"}}},
{"speaker": "Jane", "voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Puck"}}}
]
}
}
}
}' | jq -r '.candidates[0].content.parts[0].inlineData.data' \
| base64 --decode > dialogue.pcm
# Wrap raw PCM 16-bit 24kHz mono into a WAV:
ffmpeg -f s16le -ar 24000 -ac 1 -i dialogue.pcm dialogue.wav
Two ways to format the dialogue in contents.parts[0].text:
(a) Freeform (shown above) — Speaker: … line prefixes in plain text.
Simplest to generate from an LLM.
(b) Structured — explicit turn list (Python SDK only):
from google import genai
from google.genai import types
client = genai.Client(
vertexai=True,
project="YOUR_GCP_PROJECT",
location="global",
)
turns = [
types.Content(role="user", parts=[
types.Part(text="Joe: How's it going today Jane?"),
]),
types.Content(role="user", parts=[
types.Part(text="Jane: Not too bad, how about you?"),
]),
]
response = client.models.generate_content(
model="gemini-3.1-flash-tts-preview",
contents=turns,
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
speaker_voice_configs=[
types.SpeakerVoiceConfig(speaker="Joe",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore"))),
types.SpeakerVoiceConfig(speaker="Jane",
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Puck"))),
]
)
),
temperature=1.5,
),
)
Pro tip: if you want multi-speaker via the OpenAI-compatible
endpoint, pre-format the text with Speaker: prefixes and let a
single voice read both parts — the model still uses the speaker
context to vary intonation slightly. Open a ticket if you need
first-class speaker_voice_configs on /v1/audio/speech.
Audio output format
| Field | Value |
|---|---|
| Container | WAV (our gateway wraps raw PCM) |
| Codec | PCM linear 16-bit little-endian |
| Sample rate | 24 000 Hz |
| Channels | Mono (1) |
| Upstream raw | 16-bit PCM 24 kHz (no header) — we prepend the 44-byte WAV header |
Input / output limits
| Constraint | Limit |
|---|---|
Recommended /v1/audio/speech chunk |
3.5–4 KB UTF-8 for reliable prosody and retries |
Cloud Text-to-Speech direct prompt + text |
Up to 8 000 bytes total upstream; prompt and text are each limited to 4 000 bytes |
Vertex direct contents |
Up to 8 000 bytes upstream |
| Speech generation session/context | 32k tokens upstream |
| Gemini 3.1 Flash TTS Preview | 8,192 input tokens, 16,384 output tokens |
| Output audio duration | Around 655 seconds upstream; quality can degrade after several minutes |
| Per-minute rate | If a request returns HTTP 429, respect Retry-After and use bounded retries |
Latency profile
Measured 2026-04-23 against production (median of 5 cold-start requests, 60 chars input, Kore voice):
| Model | p50 | typical | Notes |
|---|---|---|---|
gemini-3.1-flash-tts-preview |
2.2 s | 2–5 s | Current API429 Gemini TTS model |
Voice / model compatibility
All five Gemini TTS models support the 30 voices listed above.
Error responses
All errors follow the OpenAI error envelope: HTTP status + a JSON body
of {"error": {"message": "...", "type": "...", "code": "..."}}. The
table covers what you'll actually encounter from /v1/audio/speech
under normal operation:
| Status | When it happens | Example body | Retryable? |
|---|---|---|---|
| 400 | A syntactically valid request is rejected by the selected TTS provider, for example empty input or an unsupported non-Gemini provider model | {"error":{"message":"input must not be empty","type":"invalid_request_error","code":"invalid_request"}} |
No — fix the request |
| 422 | Missing or blank required model, missing input, unsupported Gemini TTS ID, malformed JSON, or invalid field types |
FastAPI validation error envelope | No — fix the request |
| 401 | Missing or invalid Authorization: Bearer … header |
{"error":{"message":"Invalid authentication token","type":"invalid_request_error","code":"invalid_token"}} |
No — rotate the key |
| 413 | Provider rejects oversized input, for example Cloud/Vertex prompt + text beyond upstream byte limits |
Upstream-shaped 413 — pre-chunk, see Long-form audio below | No — split client-side |
| 429 | Per-key or per-binding rate limit hit upstream. Response carries Retry-After (seconds) |
{"error":{"message":"Rate limit exceeded","type":"rate_limit_error","code":"rate_limit"}} + Retry-After: 30 |
Yes — sleep Retry-After then retry |
| 500 | Internal service error | {"error":{"message":"Internal server error","type":"internal_error","code":"500"}} |
Yes — exponential backoff, see Retry pattern |
| 502 | Service temporarily unavailable; returned as 503 with Retry-After: 10 |
(already converted to 503; see below) | n/a |
| 503 | Service temporarily unavailable | {"error":{"message":"Backend temporarily unavailable, retry in 10 seconds","type":"backend_unavailable","code":503,"retry_after":10}} + Retry-After: 10 |
Yes — sleep Retry-After then retry |
| 504 | Long upstream stall — rare for TTS (single-shot is short) | OpenAI-shaped 504 | Yes with caution — at most 1 retry |
How to read errors safely (Python):
from openai import OpenAI, APIError, RateLimitError, APIStatusError
client = OpenAI(base_url="https://gateway.api429.com/v1", api_key="...")
try:
resp = client.audio.speech.create(model="gemini-3.1-flash-tts-preview", voice="Kore", input=text)
except RateLimitError as e: # 429 — respect Retry-After
retry_after = int(e.response.headers.get("retry-after", "30"))
...
except APIStatusError as e:
if e.status_code in (502, 503, 504): # transient — retry
retry_after = int(e.response.headers.get("retry-after", "10"))
...
elif e.status_code in (400, 401, 413): # permanent — surface
raise
else:
raise
Retry pattern
Three rules that keep retries safe and cheap:
- Honour
Retry-Afterwhen the server sets it (429 / 503 always do). That value reflects current capacity — beating it just queues you server-side without speedup. - Exponential backoff with jitter for transient 5xx without
Retry-After. Recommended schedule:
2 s → 8 s → 30 s(max 3 attempts, ±20 % jitter). - Don't retry 400/401/413 — re-issuing the same request with the same input gets the same error and burns budget. Surface it.
Reference Python implementation
import asyncio
import random
from openai import AsyncOpenAI, APIStatusError, RateLimitError
client = AsyncOpenAI(
base_url="https://gateway.api429.com/v1",
api_key="YOUR_API_KEY",
)
async def synthesize_with_retry(*, model: str, voice: str, input: str,
max_attempts: int = 4) -> bytes:
"""Synthesize speech with bounded retry. Honours Retry-After.
Returns the full WAV bytes. Raises on permanent errors or after
``max_attempts`` transient failures.
"""
backoff_s = [2, 8, 30, 60]
for attempt in range(max_attempts):
try:
resp = await client.audio.speech.create(
model=model, voice=voice, input=input,
)
return await resp.aread()
except RateLimitError as e: # 429
wait = int(e.response.headers.get("retry-after", "30"))
except APIStatusError as e:
if e.status_code in (400, 401, 413): # permanent
raise
if e.status_code in (429, 502, 503, 504, 500) and attempt < max_attempts - 1:
wait = int(e.response.headers.get("retry-after",
str(backoff_s[attempt])))
else:
raise
wait *= (1 + random.uniform(-0.2, 0.2)) # ±20 % jitter
await asyncio.sleep(wait)
raise RuntimeError("synthesize_with_retry: all attempts failed")
Reference TypeScript implementation
import OpenAI, { APIError } from "openai";
const client = new OpenAI({
baseURL: "https://gateway.api429.com/v1",
apiKey: process.env.BALANCER_API_KEY!,
});
const BACKOFF_S = [2, 8, 30, 60];
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
export async function synthesizeWithRetry(args: {
model: string;
voice: string;
input: string;
maxAttempts?: number;
}): Promise<Buffer> {
const max = args.maxAttempts ?? 4;
for (let attempt = 0; attempt < max; attempt++) {
try {
const r = await client.audio.speech.create({
model: args.model,
voice: args.voice,
input: args.input,
});
return Buffer.from(await r.arrayBuffer());
} catch (e) {
if (!(e instanceof APIError)) throw e;
const status = e.status ?? 0;
if ([400, 401, 413].includes(status)) throw e; // permanent
if (![429, 500, 502, 503, 504].includes(status)) throw e;
if (attempt === max - 1) throw e;
const headerRetry = Number(e.headers?.["retry-after"]) || BACKOFF_S[attempt];
const jittered = headerRetry * (1 + (Math.random() - 0.5) * 0.4);
await sleep(jittered * 1000);
}
}
throw new Error("synthesizeWithRetry: exhausted");
}
Cloud-only technical controls
Google Cloud Text-to-Speech exposes lower-level controls that are useful for
direct Cloud integrations, but they are not fields on our /v1/audio/speech
route.
curl -X POST "https://texttospeech.googleapis.com/v1/text:synthesize" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "x-goog-user-project: $PROJECT_ID" \
-H "Content-Type: application/json" \
-d '{
"input": {
"prompt": "Read the following in a curious, restrained tone.",
"text": "OK, so... tell me about this [uhm] AI thing."
},
"voice": {
"languageCode": "en-us",
"name": "Kore",
"model_name": "gemini-2.5-flash-tts"
},
"audioConfig": {
"audioEncoding": "LINEAR16",
"sampleRateHertz": 24000,
"speakingRate": 1.0,
"volumeGainDb": 0.0
},
"advancedVoiceOptions": {
"safetySettings": []
}
}'
advancedVoiceOptions.safetySettings is a Cloud Text-to-Speech direct API
feature. It is intentionally not documented as a balancer request field.
Legacy relax_safety_filters / safety_settings knobs are not passed through
by the gateway.
What /v1/audio/speech does NOT expose
For completeness, these controls are not fields on the narrow OpenAI-compatible speech endpoint. Some are available through the Gemini-native gateway as shown above; Cloud-only controls require a direct Google Cloud integration:
| Feature | Upstream support | Why not exposed |
|---|---|---|
temperature |
✅ Gemini-native generateContent |
Use /gemini/v1beta/models/{model}:generateContent; /v1/audio/speech stays OpenAI-compatible |
languageCode |
✅ Gemini-native / Cloud TTS direct | Gemini auto-detects on /v1/audio/speech; explicit BCP-47 is not exposed there |
| First-class multi-speaker config | ✅ Gemini-native multiSpeakerVoiceConfig / Cloud MultiSpeakerMarkup |
Use Gemini-native route or Cloud direct for speaker-to-voice mapping |
| ALAW / MULAW encodings | ✅ Cloud TTS direct unary calls | /v1/audio/speech offers mp3, opus, aac, flac, wav and pcm via response_format |
Custom sample rate (sampleRateHertz) |
✅ Cloud TTS direct | Gemini gateway path is fixed 24 kHz mono PCM |
| Streaming TTS (chunked audio) | ✅ Cloud TTS StreamingSynthesize; ✅ Vertex direct streaming |
Gemini Developer API TTS and our /v1/audio/speech are non-streaming full responses |
| Batch API (async bulk TTS) | ✅ Upstream for gemini-3.1-flash-tts-preview |
Not proxied by the balancer |
advancedVoiceOptions.safetySettings |
✅ Cloud TTS direct | Not a /v1/audio/speech request field |
| Custom voice cloning | ❌ Not supported by Google | Only 30 prebuilt voices — Google has no voice-cloning public API |
Full Google reference:
- Gemini Developer API: https://ai.google.dev/gemini-api/docs/speech-generation
- Vertex AI Gemini TTS: https://cloud.google.com/text-to-speech/docs/gemini-tts
- Interactive voice library: https://aistudio.google.com/apps/bundled/voice-library
Long-form audio (10+ minutes)
For audiobooks, podcasts, or any narration over several minutes, the
client should split the script into chunks, synthesize them in parallel,
and concatenate the WAV files locally. The gateway does split a longer
input into sentence-sized parts and returns one file, which is convenient
for paragraphs and short scenes; for 10+ minute narrations client-side
chunking still gives you per-chunk retries and progress.
Use 3.5–4 KB UTF-8 as a safe recommended chunk size. The old docs
overstated this as a local cap, but no such gateway limiter was found; the real
upstream Cloud/Vertex direct prompt + text limit is 8,000 bytes, and long
single requests can degrade in quality after several minutes. Upstream output
is around 655 seconds at the high end, but chunking remains the safer
production pattern.
Sizing math
| Target audio duration | Approximate chars (English, 13.5 ch/s) | Chunks at 3 500 bytes | Wall-clock at 8 parallel × 4 s/chunk |
|---|---|---|---|
| 30 min | ~24 000 | 7 | ~4 s |
| 60 min | ~49 000 | 14 | ~8 s |
| 90 min | ~73 000 | 21 | ~12 s |
| 120 min | ~97 000 | 28 | ~16 s |
Russian / CJK speech is slower (~10–12 ch/s), so character counts run ~25 % lower for the same duration. Cost scales linearly with input characters at the rate listed in Available models above (e.g. 90 min Flash ≈ $1.35).
Chunking strategy
- Split at sentence boundaries so prosody isn't broken mid-phrase.
- Bin-pack chunks around 3 500 bytes UTF-8 (leaving head-room for style prefixes, transcript tags, and retries).
- Preserve order — parallel synthesis must reassemble in input order on concat, not in completion order.
Parallel synthesis
Use a small, bounded number of concurrent synthesis requests and adjust it
to your account’s limits and observed responses. On HTTP 429, respect
Retry-After, back off, and limit the number of retries.
Concatenation
All Gemini TTS responses are 24 kHz mono PCM-16 WAV (see Audio output format above). Identical sample rate / channel layout means you can concatenate the audio payloads directly without re-encoding. Two practical options:
- Python
wavestdlib — read all WAVs, write one combined file. Zero external dependencies. - ffmpeg —
ffmpeg -f concat -safe 0 -i list.txt -c copy out.wavwithlist.txtlisting chunk filenames in order.
Full Python example (split → gather → concat)
import asyncio
import io
import re
import wave
from openai import AsyncOpenAI
client = AsyncOpenAI(
base_url="https://gateway.api429.com/v1",
api_key="YOUR_API_KEY",
)
CHUNK_BUDGET_BYTES = 3500 # leave room for style instructions and transcript tags
PARALLELISM = 8 # example only; adjust to account limits and observed 429s
def split_into_chunks(text: str, budget: int = CHUNK_BUDGET_BYTES) -> list[str]:
"""Split text at sentence boundaries, bin-pack to ≤budget bytes UTF-8."""
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
chunks: list[str] = []
buf = ""
for sent in sentences:
candidate = (buf + " " + sent).strip()
if len(candidate.encode("utf-8")) > budget and buf:
chunks.append(buf)
buf = sent
else:
buf = candidate
if buf:
chunks.append(buf)
return chunks
async def synthesize_one(idx: int, text: str, sem: asyncio.Semaphore) -> tuple[int, bytes]:
async with sem:
resp = await client.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Kore",
input=text,
)
return idx, await resp.aread()
async def synthesize_long(text: str, out_path: str) -> None:
chunks = split_into_chunks(text)
sem = asyncio.Semaphore(PARALLELISM)
results = await asyncio.gather(
*(synthesize_one(i, c, sem) for i, c in enumerate(chunks))
)
# Reassemble in original order (gather preserves input order, but
# we tag explicitly so partial-result paths stay safe).
results.sort(key=lambda x: x[0])
with wave.open(out_path, "wb") as out_wav:
params_set = False
for _, wav_bytes in results:
with wave.open(io.BytesIO(wav_bytes), "rb") as in_wav:
if not params_set:
out_wav.setparams(in_wav.getparams())
params_set = True
out_wav.writeframes(in_wav.readframes(in_wav.getnframes()))
# Usage:
# asyncio.run(synthesize_long(open("script.txt").read(), "narration.wav"))
Failure handling tips
- Wrap
synthesize_onein afor attempt in range(3)retry loop — individual chunks may return 429 / 5xx independently. Use bounded retries and respectRetry-After. - If one chunk consistently fails after retries, you can either fail
the whole job, or skip with silence padding (
b"\x00" * bytes_per_second * estimated_seconds) so the WAV stays the expected length — depends on whether your downstream tolerates gaps. - Track per-chunk usage: each call is billed independently
(
/api/client/usage/dailyaggregates them).
When to ask for server-side support
If you're regularly generating audio over ~30 minutes and the
client-side concat is operationally painful (e.g. mobile clients,
browser environments without wave stdlib), open a ticket — we can
prioritise a server-side /v1/audio/speech/long endpoint that
chunks, fans-out, and returns one WAV in a single HTTP response.
Integration recipes
End-to-end snippets for common products. Each is self-contained and
uses only the public /v1/audio/speech endpoint.
1. Telegram bot — voice replies
# pip install python-telegram-bot openai
import io, os
from openai import OpenAI
from telegram import Update
from telegram.ext import Application, MessageHandler, ContextTypes, filters
tts = OpenAI(
base_url="https://gateway.api429.com/v1",
api_key=os.environ["BALANCER_API_KEY"],
)
async def voice_reply(update: Update, ctx: ContextTypes.DEFAULT_TYPE):
text = update.message.text or "Hello!"
if len(text.encode("utf-8")) > 4000:
await update.message.reply_text("Sorry, message too long for TTS.")
return
speech = tts.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Kore",
input=text,
)
# Telegram accepts WAV directly via send_voice (or send_audio for file).
await update.message.reply_voice(io.BytesIO(speech.read()))
app = Application.builder().token(os.environ["TELEGRAM_BOT_TOKEN"]).build()
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, voice_reply))
app.run_polling()
2. Audiobook from a .txt file
Reuses the chunking helper from Long-form audio — wires it to a
plain text file and produces one WAV. Picks Sulafat (warm, sustained)
which works well for hours of narration.
import asyncio
from pathlib import Path
# ...split_into_chunks, synthesize_one, synthesize_long defined in
# the "Long-form audio" section above...
async def audiobook(in_path: str, out_path: str, voice: str = "Sulafat") -> None:
text = Path(in_path).read_text(encoding="utf-8")
# Override the default voice in synthesize_one by using a partial
# or just pass it through — see Long-form Python example.
await synthesize_long(text, out_path, voice=voice, model="gemini-3.1-flash-tts-preview")
# CLI: python audiobook.py book.txt narration.wav
if __name__ == "__main__":
import sys
asyncio.run(audiobook(sys.argv[1], sys.argv[2]))
3. Chat narration — LLM reply read aloud
Pipes a chat-completions response through TTS. Uses two streams in parallel: the text stream is consumed by the speaker, the audio job runs on the assembled chunks.
import os
from openai import OpenAI
llm = OpenAI(base_url="https://gateway.api429.com/v1",
api_key=os.environ["BALANCER_API_KEY"])
# 1) Get a chat reply
chat = llm.chat.completions.create(
model="claude-sonnet-5.5",
messages=[{"role": "user", "content": "Tell me a 3-sentence bedtime story."}],
max_tokens=200,
)
reply_text = chat.choices[0].message.content
# 2) TTS it (single-shot — short replies fit comfortably)
speech = llm.audio.speech.create(
model="gemini-3.1-flash-tts-preview",
voice="Despina", # smooth, calming for bedtime
input=reply_text,
)
with open("story.wav", "wb") as f:
f.write(speech.read())
4. Web-app preview button
Browser fetches via the same Bearer token. Keep the token server-side in production — this snippet is for an authenticated admin UI where the token is already in scope.
<button id="preview" data-text="Hello, this is a preview." data-voice="Puck">▶</button>
<audio id="player" controls></audio>
<script>
document.getElementById("preview").addEventListener("click", async (e) => {
const btn = e.currentTarget;
const res = await fetch("https://gateway.api429.com/v1/audio/speech", {
method: "POST",
headers: {
"Authorization": `Bearer ${window.YOUR_TOKEN}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "gemini-3.1-flash-tts-preview",
voice: btn.dataset.voice,
input: btn.dataset.text,
}),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
alert("TTS failed: " + (err.error?.message ?? res.status));
return;
}
const blob = await res.blob();
document.getElementById("player").src = URL.createObjectURL(blob);
document.getElementById("player").play();
});
</script>
Quickstart: the first request · Models and prices · Get an API key