---
title: 'Natural Cantonese Voiceover with Gemini 3.8 Flash TTS: Step by Step, and the Pitfalls'
author: Forrest Xi
date: '2026-10-02'
url: https://blog.maxwell-x.dev/en/gemini-tts-cantonese/
lang: en
tags:
- TTS
- Gemini
- Cantonese
---

# Natural Cantonese Voiceover with Gemini 3.8 Flash TTS: Step by Step, and the Pitfalls

> We voiced a 30-second tech promo in Cantonese and fixed it one problem at a time: the model read the directions aloud, slipped into Mandarin, spoke its English with an American accent, and said "14 seconds" instead of "14 minutes". This post gives runnable requests for each step, why each step is there, and before/after audio for every pitfall.

::: tldr
**TL;DR**

- **Put only the words to be spoken in the text.** Gemini 3.8 TTS treats `text` as a verbatim transcript. With directions written into the text, 6 of 10 takes read the directions aloud. Put style in `speechMetadata.style`, as one short phrase.
- **Get the accent from the voice, not the prompt.** We went through all 2,089 prebuilt and Extended Voice Library voices: none is Cantonese or Chinese, and the English comes out in a standard American or British accent. A voice built with voice design from a text description gave us Hong Kong-accented English.
- **Write the script in traditional Cantonese characters, not simplified.** The model detects the language itself. The same line in simplified characters came out in Mandarin 2 times out of 4; in traditional Cantonese characters with "Hong Kong Cantonese" in the style, 10 of 10 were Cantonese.
- **It is cheap.** We measured 25 tokens per second of audio, so a minute of speech costs about $0.027 at the 2027 list price, half that during the promotion.
- **Check every take word by word.** "14 分鐘" (14 minutes) came out as "14 秒" (14 seconds) once and as "1.4 分鐘" once; after we wrote the number in Chinese characters (十四), it did not happen again. There is no reliable automatic check for accent; you have to listen.
:::

## The example: a 30-second Cantonese promo

This is the finished video. It is about [cutting Hy4's cold compile on TPU v7 from 95 minutes to 14](https://blog.maxwell-x.dev/en/hy4-cold-compile/). The narration is colloquial Cantonese mixed with English, the way Hong Kong engineers talk, and all of it was generated by `gemini-3.8-flash-tts`; there is no human recording.

<figure>
<video controls playsinline preload="metadata" poster="https://blog.maxwell-x.dev/gemini-tts-cantonese/video-poster.jpg" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/hy4-promo-yue.mp4" style="display:block;width:100%;max-width:360px;margin:0 auto;border-radius:8px"></video>
<figcaption>Cantonese promo, 30.5 s. Five lines of narration, each generated separately and placed to the picture.</figcaption>
</figure>

The five lines:

| Beat | Cantonese script (as sent to TTS) | Meaning |
|---|---|---|
| Problem | 混元 4 喺 TPU v7 度 cold start，淨係 compile 就要 95 分鐘；cache 一 invalidate 咗，就要由頭嚟過。 | Hy4's cold start on TPU v7 spends 95 minutes just compiling; once the cache is invalidated, you start over. |
| Turn | Bottleneck 唔喺 compiler 度，係個 graph 畀人放大咗。 | The bottleneck isn't the compiler; the graph got blown up. |
| Fix | Loop 改用 for i，constant 改做 parameter，compile 出嚟嘅嘢喺唔同 rank 之間 share。 | Loops use fori, constants become parameters, compiled artifacts are shared across ranks. |
| Result | Cold start，直接壓到得返十四分鐘！ | Cold start, cut straight down to fourteen minutes! |
| Payoff | 每日嘅優化實驗由 12 組變 80 組，i-te-rate 快咗好多！ | Daily optimization experiments went from 12 to 80; we iterate much faster! |

The way the last two lines are written (十四 in characters, a hyphenated "i-te-rate") came from fixing pitfalls, explained below.

## Meet Gemini 3.8 Flash TTS

[Gemini 3.8 Flash TTS](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/gemini/3-8-flash-tts) (`gemini-3.8-flash-tts`) is Google's flagship text-to-speech model, released on September 28, 2026 and currently in Preview. You call it through the Gemini Enterprise (Vertex AI) `generateContent` / `streamGenerateContent` methods. Google positions it around four things:

- **Expressiveness**: a wide emotional range and natural cadence, following turn-level `style` directions and inline vocal tags such as `<laugh>`, `<sigh>` and `<short pause>`.
- **Long-form stability**: voice identity, timbre, volume and room tone stay consistent across long dialogues and multi-minute narration.
- **Regional accents**: 130 languages, including regional accents and minority dialects. You don't specify the language; the model [detects it from the input](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/overview). Cantonese is on the supported list, and Chinese is listed separately as Hans and Hant script.
- **Voices**: 30 prebuilt voices, more than 2,000 voices in the Extended Voice Library, voices you create from a text description with [voice design](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/voice-design), and voices replicated from a recording with voice replication.

There is also a Flash-Lite model in the same generation. Both use the same request schema, so switching is a change of model ID:

| | Flash TTS | Flash-Lite TTS |
|---|---|---|
| Model ID | `gemini-3.8-flash-tts` | `gemini-3.8-flash-lite-tts` |
| Strength | Voice fidelity, acting nuance, dialect coverage | Throughput, low latency, cost |
| Recommended for | Audiobooks, studio narration, complex multi-speaker dialogue, frequent vocal tags, difficult pronunciation, regional dialects | High-volume production, real-time voice agents, read-aloud features, voice replication, everyday single-speaker speech |
| Languages | 130 | 101 |

We wanted natural Cantonese, which falls under regional dialects, so we used Flash. We did not test Flash-Lite.

A few specs worth knowing before you integrate:

| Item | Spec |
|---|---|
| Input / output | Text in, audio out only |
| Token limits | 8,192 input, 16,384 output |
| Region | `global` only |
| Speakers | One or two. For more than two, or to mix in designed voices, synthesize each turn and concatenate the audio yourself |
| Output format | Unary requests default to a complete WAV file (16-bit PCM, 24 kHz, mono); streaming defaults to raw PCM; μ-law / A-law are also available. No MP3 or Ogg Opus, and the sample rate can't be set |
| Billing | Pay-as-you-go |

If you have used an earlier Gemini TTS model (such as `gemini-3.1-flash-tts-preview`), three of the changes in the [migration guide](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/migration-guide) matter most for prompting: `text` is a verbatim transcript and style moves to `speechMetadata.style`; vocal tags change from square brackets `[sigh]` to angle brackets `<sigh>`; and `systemInstruction` is gone, while sampling parameters such as `temperature` are rejected. Step 2 below covers the first of these, which was also the first pitfall we hit.

### Strengths: why it is worth using

Google's stated strengths, plus what we saw in practice:

- **Dialects actually work.** It supports 130 languages and says explicitly that this includes regional accents and minority dialects. We produced Hong Kong engineer-style Cantonese with English terms mixed into Cantonese sentences, and the switches sound natural rather than stitched together.
- **Fine-grained control.** Each line can have its own style, and lines can carry vocal tags such as `<laugh>` and `<sigh>`. Text is treated as a verbatim transcript, so it reads what you wrote instead of rewording it. The flip side is in Step 2: directions written into the text get read too.
- **Customizable voices.** Besides 30 prebuilt voices and more than 2,000 in the Extended Voice Library, you can design a voice from a sentence or two (ours took a few seconds) or replicate one from a recording. Accent, age and timbre are all yours to set, which is what got us Hong Kong-accented English.
- **Long-form stability** (per Google). Voice, volume and room tone stay consistent over long dialogues and multi-minute narration. Our video is 30 seconds, so we did not verify this.
- **One API, two tiers.** Flash and Flash-Lite share the request schema: Flash for quality, Flash-Lite for latency and cost, switched by changing the model ID.
- **Cheap**, see the next section.

### Pricing: roughly one to three US cents per minute of speech

From the [official Gemini Enterprise pricing](https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing) (USD per 1M tokens):

| Model | Period | Text input | Audio output |
|---|---|---:|---:|
| Flash TTS | Through 2026-12-31 (promotional) | 0.50 | 9.00 |
| Flash TTS | From 2027-01-01 | 1.00 | 18.00 |
| Flash-Lite TTS | Through 2026-12-31 (promotional) | 0.50 | 6.00 |
| Flash-Lite TTS | From 2027-01-01 | 1.00 | 12.00 |

The promotional price takes the form of 50% credits back on net spend on the same model, not a direct discount.

Almost all of the cost is audio output. We read `usageMetadata` from the responses: both measurements came to **25 tokens per second of audio** (99 tokens for 3.96 s, 130 for 5.2 s). For Flash TTS that works out to:

| | Promotional | From 2027 |
|---|---:|---:|
| Per minute of speech (1,500 tokens) | $0.0135 | $0.027 |
| Per hour of speech (90,000 tokens) | $0.81 | $1.62 |

Text input is a few dozen tokens per line and can be ignored. The five lines of our video, including the takes our checks sent back, came to 1,118 audio tokens, or $0.02 at the 2027 list price; designing a voice took about 220 input and 560 output tokens, about $0.01. The transcription calls used for checking are billed separately at the transcription model's rates and are not included.

## Step 1: Write a colloquial Cantonese script, not a Mandarin script read in Cantonese

Hand a Mandarin script to TTS and ask for Cantonese, and you get written Chinese read aloud in Cantonese, which any Hong Konger can tell at once. Rewrite the script as speech first:

- **Use spoken Cantonese words**: 在 → 喺 (at), 是 → 係 (is), 了 → 咗 (perfective), 重来 → 由頭嚟過 (start over), 只剩 → 得返 (only ... left).
- **Keep technical terms in English**: Hong Kong engineers say cold start, compile, cache and bottleneck in everyday speech. Translating them all into Chinese sounds less natural, not more.
- **Keep the takeaway in Chinese for non-technical viewers**, for example 優化實驗 (optimization experiments).

This step decides whether it sounds like a Hong Konger talking, and the model can't do it for you.

## Step 2: Only the spoken words go in the text; style goes in `speechMetadata.style`

This is the easiest trap when moving from older TTS models. With older models such as `gemini-3.1-flash-tts-preview`, the usual practice was to write the style into the text: "Read this in an excited tone: …". For 3.8, the [official migration guide](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/migration-guide) says `text` is read as a verbatim transcript, and directions written into it "might be spoken aloud".

What we measured: keeping the old style of prompt (directions in the text, script fenced in quotes), two takes for each of the five lines, **6 takes read the whole direction aloud**, and lines that should run 3–8 s ran 17–40 s.

<figure>
<audio controls preload="none" style="width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/01-leak.mp3"></audio>
<figcaption>Counter-example (first 13 s): the model starts with "Read only the text inside the quotes, do not read this instruction…", in Cantonese.</figcaption>
</figure>

The correct request looks like this. Style goes in `speechMetadata.style` as one short phrase; `text` holds only the lines:

```python
import base64, subprocess, requests

URL = ("https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/"
       "publishers/google/models/gemini-3.8-flash-tts:generateContent")
TOKEN = subprocess.check_output(["gcloud", "auth", "print-access-token"], text=True).strip()

def tts(text, style, voice, out_path):
    body = {
        "contents": [{"role": "user", "parts": [{
            "text": text,                                  # only the words to be spoken
            "speechMetadata": {"style": style},            # style: one short phrase
        }]}],
        "generationConfig": {
            "responseModalities": ["AUDIO"],
            "speechConfig": {"languageCode": "yue-HK", "voiceConfig": {"voice": voice}},
        },
    }
    r = requests.post(URL, headers={"Authorization": f"Bearer {TOKEN}"}, json=body, timeout=180)
    r.raise_for_status()
    data = r.json()["candidates"][0]["content"]["parts"][0]["inlineData"]["data"]
    with open(out_path, "wb") as f:
        f.write(base64.b64decode(data))                    # unary requests return a complete WAV file
```

The styles we ended up with: one shared base, plus one mood per line.

```python
BASE = "Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings"
STYLE = {"problem": BASE + ", heavy and urgent",    "turn": BASE + ", calm and assured",
         "fix": BASE + ", confident and upbeat",     "result": BASE + ", energetic, pleasantly surprised",
         "payoff": BASE + ", rising excitement, strong finish"}
```

Related changes to watch for:

- **`systemInstruction` is no longer supported.** Moving the directions into a system message is not a way around this.
- **`temperature` / `topP` / `topK` are rejected with `INVALID_ARGUMENT`**; remove them from the request.
- **Unary requests return a complete WAV file** that starts with a `RIFF` header. If your old code treats the response as raw PCM and wraps its own WAV header around it, the header bytes get played as audio: a very short click at the start.
- If you call the model through an OpenAI-compatible middle layer, **first check that it passes `speechMetadata` through.** How to check is in Step 6: set the style to "extremely slow, one syllable at a time" and see whether the duration grows.

## Step 3: Let the voice carry the accent; build a Hong Kong voice with voice design

With the prebuilt voice Puck, the Cantonese itself was fine, but the English in each line had a standard American or British accent, which is not how Hong Kongers talk. The [prompting guide](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/prompting-guide) says fixed traits such as age, gender and regional accent belong to the voice, not to `style`.

The catch is that the voice library has no such voice. We paged through the whole Voices API list: 30 prebuilt voices plus the Extended Voice Library, 2,089 in all, with language codes concentrated in en / ko / ja / hi / pt / ar / de and similar, and **not one Cantonese or Chinese voice**.

So the only option is [voice design](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/voice-design): describe the voice in a sentence or two, and the API generates it, stores it in your project and returns a `voice_…` ID that you use like a prebuilt voice.

```python
VOICES = "https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/voices"
body = {"store": True, "voice": {
    "type": "VOICE_TYPE_PROMPTED",
    "displayName": "hk-engineer",
    "gender": "male",
    "languageCode": "yue-HK",
    # "A Hong Kong male engineer in his thirties, speaking natural colloquial Hong Kong Cantonese; the English terms
    #  in his sentences carry a clear Hong Kong accent (not standard American or British); clear, confident,
    #  like a tech keynote narrator."
    "prompted": {"input": "三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音"
                          "（唔系标准英美音），声音清晰、自信，似科技发布会旁白。"},
}}
r = requests.post(VOICES, headers={"Authorization": f"Bearer {TOKEN}"}, json=body, timeout=120)
voice_id = r.json()["id"]                 # like voice_xxxxxxxx-...; pass it as voiceConfig.voice
# r.json()["sample_audio"] is a preview: audio/l16, 24 kHz mono raw PCM; add a WAV header yourself
```

We built two, one from an English description and one from the Chinese description above, generated the full narration with each, and a listener picked the one built from the Chinese description.

<div class="tw"><table>
<tr><td>Prebuilt voice Puck</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/03-puck.mp3"></audio></td></tr>
<tr><td>Designed voice (Hong Kong engineer)</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/03-designed.mp3"></audio></td></tr>
</table></div>

Two things to note:

- **Creating a voice is billed** (as text input plus audio output tokens; about 220 in and 560 out for ours). Speech generated with it is billed at the normal rate.
- **Stored voices expire after a year without use**; each use resets the clock. For a long-running project, keep the description so you can recreate the voice if it expires.

## Step 4: Traditional Cantonese characters keep Mandarin out

The documentation says 3.8 [detects the input language automatically](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/text-to-speech/overview). We set `languageCode: yue-HK` in the request, but while the Cantonese script was written in simplified characters (系, 个, 钟), the result line still came out entirely in Mandarin from time to time.

For the result line, "Cold start，直接压到得返 14 分钟！", same voice, several takes per variant:

| Script | Takes read in Mandarin |
|---|---:|
| Simplified-character Cantonese | 2 / 4 |
| Traditional Cantonese characters | 1 / 4 |
| Traditional Cantonese characters + `Hong Kong Cantonese` in the style | 0 / 10 |

The other four lines never came out in Mandarin with any variant. The one that did is the shortest line, and the only one that starts in English. We have not verified why it is more likely to be taken as Mandarin; we only observed it.

<div class="tw"><table>
<tr><td>Simplified script: whole line in Mandarin</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/02-mandarin.mp3"></audio></td></tr>
<tr><td>Traditional characters + Hong Kong Cantonese</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/02-cantonese.mp3"></audio></td></tr>
</table></div>

We use "Hong Kong Cantonese" in the style to steer the **language**, not the accent: with the same phrase, the prebuilt voice still spoke standard English. The accent comes from the voice in Step 3.

## Step 5: Don't stack speed-ups, and don't rely on tags for pauses

Two habits from our old pipeline made the pacing worse:

- **Stacked speed-ups.** To fit 30 seconds, the old pipeline put "speaking rapidly" in the style and then sped the audio up again with ffmpeg `atempo=1.07`. On 3.8 it was clearly too fast. With both removed, the full Cantonese narration went from 22.1 s to 27.7 s (same voice). The final video grew from 30 s to 30.5 s, with a voice change and two re-recorded lines in between.
- **A pause tag that is too long.** For a short pause after "Cold start" we used the official `<short pause>` tag, and measured a 0.86 s gap, which sounds like a break. With the tag removed and only the comma left, the pause is about 0.3 s and sounds natural.

`<short pause>` / `<long pause>` from the guide are for places that need real silence. For phrasing, punctuation is enough.

## Step 6: Check every take word by word

The same line comes out differently on every take, and if you generate enough, some will be wrong. What we ran into:

- "14 分鐘" (14 minutes) came out as "**14 秒**" (14 seconds), and that take was already in the video before a listener caught it;
- another take said "**1.4 分鐘**" (1.4 minutes);
- and the whole-line Mandarin takes described above.

<div class="tw"><table>
<tr><td>"14 seconds", and a 0.86 s gap after Cold start</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/04-14sec.mp3"></audio></td></tr>
<tr><td>Fixed: number written as 十四, pause tag removed</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/04-fixed.mp3"></audio></td></tr>
</table></div>

With the number written in digits, 2 of 5 takes were wrong ("14 秒", "1.4 分鐘"); written as 十四, all 4 takes were right. The samples are small, but rewriting costs nothing, so we recommend writing numbers in characters.

The acceptance checks we settled on, run on every take:

1. **Two transcription models, word by word** (we used Gemini 3.5 Flash and 3.7 Flash). A take passes only if both match the script. A single transcription model mishears too (it turned 混元 into other words), so don't trust just one.
2. **Cut long audio into short chunks before transcribing.** On a whole take, the model summarized away the direction that had been read aloud and returned a clean-looking transcript; we were fooled by this once. Cut at the pauses into chunks a few seconds long, and transcribe those.
3. **Look at the duration.** A take several times longer than the normal length of the same line almost always means the directions were read aloud. This check is the cheapest and the most reliable.
4. **Measure the longest pause inside the line** (`ffmpeg -af silencedetect`); listen to anything over about 0.5 s.
5. **Check the language.** Have a transcription model report the share of characters pronounced in Cantonese. Before relying on it, run it on a known Cantonese sample and a known Mandarin sample and confirm it tells them apart (we got 100 and 0).

**There is no reliable automatic check for accent.** We asked a model to rate the Hong Kong accent of the English words from 1 to 5, and every sample got 3, including Puck with its standard American accent, so the rating could not tell anything apart. Accent has to be judged by ear.

## Step 7: If a single English word still sounds American, change its spelling

With the designed voice, most of the English already sounded like Hong Kong, but a listener still flagged "iterate" in the payoff line as too American. We made three candidates to choose from by ear:

- the same script, generated again;
- `English words in a Hong Kong accent` added to the style;
- the spelling changed to **`i-te-rate`**, so the three syllables get even weight.

The respelling won. That was a listener's choice, not a measurement, and it may not work as well for other words. But respelling costs almost nothing, so it is worth trying first.

<div class="tw"><table>
<tr><td>Original spelling: iterate</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/05-iterate-us.mp3"></audio></td></tr>
<tr><td>Respelled: i-te-rate</td><td><audio controls preload="none" style="width:240px;max-width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/05-iterate-hk.mp3"></audio></td></tr>
</table></div>

## A small trap when cutting it into the video

The narration is generated line by line, and the on-screen cards and number hits have to land with the speech. We locate them by the pauses in each line's audio; the hit on "80 組" (80 runs), for example, was placed at the **longest pause** in the payoff line.

With the new voiceover, the two longest pauses differed by 2 ms (0.351 s vs 0.349 s), the code picked the earlier one, and the hit landed about 2.6 s early. We changed the rule to "the pause nearest 60% of the line" and re-ran it on the old voiceovers to confirm it picks the same positions there.

This has nothing to do with TTS, but it can trigger every time the voiceover is regenerated: **an anchor chosen by "the maximum" fails at random when values are nearly tied.**

## The complete prompts and script

Put the seven steps together and you get the script below. It does four things: creates a voice from the description if you don't pass one; synthesizes each line; runs the Step 6 checks on every take (duration, longest pause, keywords in two transcriptions, Cantonese share) and regenerates a line that fails, up to 4 times; and finally trims the silence, joins the lines into one narration, and reports token usage and cost.

All the prompts it uses:

| Purpose | Content |
|---|---|
| Voice description (used once, to create the voice) | 三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音（唔系标准英美音），声音清晰、自信，似科技发布会旁白。 ("A Hong Kong male engineer in his thirties … like a tech keynote narrator", see Step 3) |
| Style base (on every line) | `Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings` |
| Per-line mood | heavy and urgent / calm and assured / confident and upbeat / energetic, pleasantly surprised / rising excitement, strong finish |
| Lines | The five lines at the top of this post, in traditional Cantonese characters |

[Download make_voiceover.py](https://blog.maxwell-x.dev/gemini-tts-cantonese/make_voiceover.py). Requirements: Python 3 with `requests`, and `ffmpeg` / `ffprobe` on PATH; run `gcloud auth login` first, and the project needs Vertex AI enabled.

```bash
export PROJECT_ID=your-project
export VOICE_ID=voice_...        # optional: reuse a designed voice; if unset, one is created and its ID printed
python3 make_voiceover.py
```

```python
#!/usr/bin/env python3
"""Cantonese voiceover with Gemini 3.8 Flash TTS: one take per line, checked, then joined.

    export PROJECT_ID=your-project        # Vertex AI enabled; `gcloud auth login` done
    export VOICE_ID=voice_...             # optional: reuse a designed voice; omitted -> one is created
    python3 make_voiceover.py             # -> out/line*.wav, out/narration.wav

Needs: python3 + requests, ffmpeg/ffprobe on PATH.
"""
import base64, io, json, os, re, subprocess, tempfile, time, wave
import requests

PROJECT = os.environ["PROJECT_ID"]
API = f"https://aiplatform.googleapis.com/v1beta1/projects/{PROJECT}/locations/global"
TOKEN = subprocess.check_output(["gcloud", "auth", "print-access-token"], text=True).strip()
HDR = {"Authorization": f"Bearer {TOKEN}"}
OUT = "out"; GAP = 0.4; MAX_TAKES = 4
PRICE_PER_M = {"text_in": 1.00, "audio_out": 18.00}   # USD per 1M tokens from 2027-01-01 (half that through 2026)

# --- the voice: accent, age and timbre live here, not in the style ---------------------------
VOICE_PROMPT = ("三十多岁的香港男工程师，讲地道香港粤语口语，句中夹杂的英文术语带明显港式口音"
                "（唔系标准英美音），声音清晰、自信，似科技发布会旁白。")

# --- the script: text is read verbatim; style is one short phrase per line --------------------
BASE = "Hong Kong Cantonese, tech keynote narrator, steady pace, crisp endings"
LINES = [  # (text in traditional Cantonese characters, mood, must appear in transcript, must not appear)
    ("混元 4 喺 TPU v7 度 cold start，淨係 compile 就要 95 分鐘；cache 一 invalidate 咗，就要由頭嚟過。",
     "heavy and urgent", [r"95", r"分[鐘钟]"], []),
    ("Bottleneck 唔喺 compiler 度，係個 graph 畀人放大咗。", "calm and assured", [r"(?i)compiler", r"(?i)graph"], []),
    ("Loop 改用 for i，constant 改做 parameter，compile 出嚟嘅嘢喺唔同 rank 之間 share。",
     "confident and upbeat", [r"(?i)constant", r"(?i)parameter"], []),
    ("Cold start，直接壓到得返十四分鐘！", "energetic, pleasantly surprised", [r"14|十四", r"分[鐘钟]"],
     [r"秒", r"1\.4"]),                                             # misreadings we actually heard
    ("每日嘅優化實驗由 12 組變 80 組，i-te-rate 快咗好多！", "rising excitement, strong finish", [r"12|十二", r"80|八十"], []),
]


def post(path, body, timeout=180):
    r = requests.post(f"{API}/{path}", headers=HDR, json=body, timeout=timeout)
    r.raise_for_status()
    return r.json()


def create_voice():
    j = post("voices", {"store": True, "voice": {
        "type": "VOICE_TYPE_PROMPTED", "displayName": "hk-engineer", "gender": "male",
        "languageCode": "yue-HK", "prompted": {"input": VOICE_PROMPT}}}, timeout=120)
    print("created voice", j["id"], "- export VOICE_ID to reuse it")
    return j["id"]


def synth(text, style, voice):
    j = post("publishers/google/models/gemini-3.8-flash-tts:generateContent", {
        "contents": [{"role": "user", "parts": [{"text": text, "speechMetadata": {"style": style}}]}],
        "generationConfig": {"responseModalities": ["AUDIO"],
                             "speechConfig": {"languageCode": "yue-HK", "voiceConfig": {"voice": voice}}}})
    wav = base64.b64decode(j["candidates"][0]["content"]["parts"][0]["inlineData"]["data"])  # complete WAV
    return wav, j.get("usageMetadata", {})


def ffmpeg(*args, data=None):
    return subprocess.run(["ffmpeg", "-nostdin", "-v", "error", "-y", *args], input=data,
                          capture_output=True, check=True).stdout


def trim(wav):  # cut leading/trailing silence, short fades against clicks
    edge = "silenceremove=start_periods=1:start_threshold=-42dB"
    with tempfile.NamedTemporaryFile(suffix=".wav") as f:   # a file, not a pipe, so the WAV header gets real sizes
        ffmpeg("-i", "pipe:0", "-af", f"{edge},areverse,{edge},areverse,afade=t=in:d=0.01,areverse,"
               "afade=t=in:d=0.04,areverse", f.name, data=wav)
        return open(f.name, "rb").read()


def duration(wav):
    w = wave.open(io.BytesIO(wav)); return w.getnframes() / w.getframerate()


def longest_pause(wav):
    log = subprocess.run(["ffmpeg", "-nostdin", "-i", "pipe:0", "-af", "silencedetect=n=-38dB:d=0.12", "-f", "null", "-"],
                         input=wav, capture_output=True).stderr.decode()
    st = [float(x) for x in re.findall(r"silence_start: ([\d.]+)", log)]
    en = [float(x) for x in re.findall(r"silence_end: ([\d.]+)", log)]
    return max([b - a for a, b in zip(st, en)] or [0.0])


def ask(model, prompt, wav):
    body = {"contents": [{"role": "user", "parts": [
        {"text": prompt}, {"inlineData": {"mimeType": "audio/wav", "data": base64.b64encode(wav).decode()}}]}]}
    for attempt in range(3):         # now and then a response comes back with no text
        j = post(f"publishers/google/models/{model}:generateContent", body)
        parts = (j.get("candidates") or [{}])[0].get("content", {}).get("parts", [])
        text = "".join(p.get("text", "") for p in parts).strip()
        if text:
            return text
        time.sleep(2 * (attempt + 1))
    return ""                        # an empty transcript fails the check, so the line is generated again


def check(text, wav, must, forbid):
    """Return a list of problems; empty means the take passes."""
    problems, dur = [], duration(wav)
    units = (len(re.findall(r"[\u4e00-\u9fff]", text)) + len(re.findall(r"[A-Za-z]+(?:-[A-Za-z]+)*", text))
             + len(re.findall(r"\d+", text)))                      # Chinese characters + English words + numbers
    if dur > 1.5 + 0.3 * units:     # normal takes ran 0.23-0.29 s/unit; takes that read the directions ran 3-12x
        problems.append(f"too long ({dur:.1f}s)")
    pause = longest_pause(wav)
    if pause > 0.6:                                                 # 0.86 s read as a break; commas give ~0.3 s
        problems.append(f"pause {pause:.2f}s")
    for model in ("gemini-3.5-flash", "gemini-3.7-flash"):          # two transcribers must both agree
        heard = ask(model, "逐字转写这段粤语音频，数字用阿拉伯数字，只输出转写。", wav)
        miss = [m for m in must if not re.search(m, heard)] + [f for f in forbid if re.search(f, heard)]
        if miss:
            problems.append(f"{model} heard {heard!r} (check {miss})")
    js = ask("gemini-3.5-flash", '判断音频里每个中文字是粤语还是普通话发音（英文词忽略）。'
             '只输出 JSON：{"cantonese_pct": 0-100}', wav)
    m = re.search(r"\{.*\}", js, re.S)
    pct = json.loads(m.group(0)).get("cantonese_pct", 0) if m else 0
    if pct < 90:
        problems.append(f"Mandarin drift (cantonese_pct={pct})")
    return problems


def main():
    os.makedirs(OUT, exist_ok=True)
    voice = os.environ.get("VOICE_ID") or create_voice()
    tokens = {"text_in": 0, "audio_out": 0}
    takes = []
    for i, (text, mood, must, forbid) in enumerate(LINES, 1):
        for n in range(1, MAX_TAKES + 1):
            wav, usage = synth(text, f"{BASE}, {mood}", voice)
            tokens["text_in"] += usage.get("promptTokenCount", 0)
            tokens["audio_out"] += usage.get("candidatesTokenCount", 0)
            wav = trim(wav)
            problems = check(text, wav, must, forbid)
            print(f"line {i} take {n}: {duration(wav):.2f}s", "OK" if not problems else problems)
            if not problems:
                break
        else:
            raise SystemExit(f"line {i}: no clean take in {MAX_TAKES} tries; listen to out/line{i}.wav")
        path = f"{OUT}/line{i}.wav"
        open(path, "wb").write(wav); takes.append(path)
    gap = f"{OUT}/gap.wav"
    ffmpeg("-f", "lavfi", "-i", "anullsrc=r=24000:cl=mono", "-t", str(GAP), gap)
    with open(f"{OUT}/list.txt", "w") as f:
        f.write("".join(f"file '{os.path.abspath(p)}'\nfile '{os.path.abspath(gap)}'\n" for p in takes[:-1])
                + f"file '{os.path.abspath(takes[-1])}'\n")
    ffmpeg("-f", "concat", "-safe", "0", "-i", f"{OUT}/list.txt", "-ar", "24000", "-ac", "1", f"{OUT}/narration.wav")
    cost = sum(tokens[k] * PRICE_PER_M[k] / 1e6 for k in tokens)
    print(f"narration: {OUT}/narration.wav  tokens {tokens}  TTS cost ${cost:.4f} (list price from 2027; "
          f"half through 2026; transcription calls billed separately)")


if __name__ == "__main__":
    main()
```

One real run produced the output below. Line 1's first take was sent back for a 0.72 s pause plus one transcriber returning no text, and line 3's first take for a 0.63 s pause; everything else passed first time:

```text
line 1 take 1: 8.10s ['pause 0.72s', "gemini-3.7-flash heard '' (check ['95', '分[鐘钟]'])"]
line 1 take 2: 7.66s OK
line 2 take 1: 3.93s OK
line 3 take 1: 7.24s ['pause 0.63s']
line 3 take 2: 5.97s OK
line 4 take 1: 2.72s OK
line 5 take 1: 4.76s OK
narration: out/narration.wav  tokens {'text_in': 295, 'audio_out': 1118}  TTS cost $0.0204 (list price from 2027; half through 2026; transcription calls billed separately)
```

The narration the script produced (26.6 s, no music):

<figure>
<audio controls preload="none" style="width:100%" src="https://blog.maxwell-x.dev/gemini-tts-cantonese/06-script-output.mp3"></audio>
<figcaption>Output of make_voiceover.py, out/narration.wav. Every run comes out slightly different.</figcaption>
</figure>

Two notes: the cost line uses the list price from 2027, which is halved during the promotion; the Gemini 3.5 / 3.7 Flash calls made by the checks are billed separately.

## Pitfall checklist

| Pitfall | Symptom | What to do |
|---|---|---|
| Style written into the text | Directions read aloud; seconds become tens of seconds (6/10) | Style in `speechMetadata.style`; text holds only the lines |
| Middle layer drops the field | Style has no effect at all | Use an "extremely slow" style and check the duration, to confirm `speechMetadata` is passed through |
| Prebuilt voice reads English | Standard American or British accent | No Cantonese voice among prebuilt or Extended Library voices; build a Hong Kong voice with voice design |
| Cantonese in simplified characters | Short line comes out entirely in Mandarin (2/4) | Traditional Cantonese characters + Hong Kong Cantonese in the style (0/10) |
| Stacked speed-ups | Too fast | Drop "speaking rapidly" and atempo |
| `<short pause>` | A clear 0.86 s break | Phrase with punctuation; keep tags for real silence |
| Numbers in digits | "14 秒", "1.4 分鐘" | Write numbers in characters |
| Checking one thing only | Misread words slip through | Two transcription models word by word + duration + pauses + language |
| Transcribing the whole take | Directions read aloud get summarized away | Cut into chunks of a few seconds, then transcribe |
| One English word sounds American | e.g. iterate | Respell it (i-te-rate) and pick by ear |
| WAV header | A click at the start | Unary responses are complete WAV files; don't add another header |

::: postscript
All numbers in this post come from this one voiceover. Each variant was generated only 4–10 times, so these are directional observations, not statistics. "Read in Mandarin" was judged by a transcription model that we first checked on known Cantonese and known Mandarin samples; accent was judged by ear.
:::
