Gemini 3.1 Flash TTS: SAFETY / incomplete audio on neutral Spanish narration

Hello Google team,

I need help distinguishing a generation/backend failure from a content restriction in gemini-3.1-flash-tts-preview. A short neutral Spanish narration succeeded (10.2 seconds), but an independent 480-word text about maps, scales, colours and terrain returned no audio with finishReason SAFETY and an incomplete-stream message. A longer historical documentary narration had returned the same error previously. We have stopped resubmitting the documentary pending clarification.

Configuration:

  • REST POST /v1beta/models/gemini-3.1-flash-tts-preview:generateContent (unary, NOT streaming).
  • responseModalities: [“AUDIO”].
  • speechConfig.voiceConfig.prebuiltVoiceConfig.voiceName: “Charon”.
  • maxOutputTokens: 16384; client timeout: 300 seconds.
  • No custom temperature/topP or safety settings.
  • No HTTP 429 or quota-exhausted message.
  • Date observed: 28 October 2026.

The failed neutral test returned:

finishReason: SAFETY
finishMessage: The audio stream could not be completed. Please retry your request, or try your request in unary mode if streaming continues to fail. You can also modify your input text slightly, or select a different voice.
promptFeedback: null
promptTokenCount: 793
totalTokenCount: 793

The client was already using unary mode. A supported maxOutputTokens value did not resolve the failure. The request explicitly instructs speech synthesis and separates voice direction from the verbatim transcript.

Successful short control transcript:
“Bienvenidos a Geo en Corto. Hoy vamos a descubrir una historia a través de sus mapas.”

Independent neutral long transcript (480 words)

Un mapa es una manera de representar un lugar para comprenderlo mejor. Puede mostrar un continente entero, una región, una ciudad o un pequeño jardín. En todos los casos, el dibujo selecciona algunas características del espacio y deja otras fuera. Esa selección depende de la pregunta que queremos responder. Para encontrar una plaza necesitamos calles. Para entender una cordillera necesitamos alturas. Para planear un paseo junto al río necesitamos senderos, puentes y accesos.

La escala nos permite relacionar el tamaño del dibujo con el tamaño del mundo. Si acercamos mucho la vista, podemos distinguir detalles pequeños, pero perdemos parte del contexto. Si nos alejamos, aparecen relaciones entre lugares que antes no cabían en la pantalla. Ninguna de esas vistas es siempre mejor. Cada una sirve para explicar una parte diferente de la misma historia. Por eso una buena presentación puede empezar con una vista amplia y acercarse después a un punto concreto.

Los colores también ayudan a leer el paisaje. Un azul suave puede representar el agua. Los tonos de la tierra pueden sugerir vegetación, zonas secas o diferencias de altura. Sin embargo, un color necesita un significado claro. No basta con que el mapa sea bonito. Si usamos un mismo tono para explicar dos cosas distintas, el espectador puede confundirse. Una leyenda breve permite entender qué representa cada símbolo sin tener que adivinarlo. La claridad resulta especialmente importante en una pantalla pequeña.

Las curvas de nivel unen puntos que tienen la misma altura. Cuando aparecen muy juntas, indican una pendiente pronunciada. Cuando están separadas, el terreno suele ser más suave. Con un poco de práctica podemos reconocer un valle, una colina o una meseta sin ver una fotografía. Las sombras del relieve ofrecen otra ayuda visual, aunque dependen de la dirección de la luz imaginada. Conviene mantener esa dirección constante para que las montañas se perciban de forma coherente.

Los ríos conectan partes del paisaje. Podemos seguir su recorrido desde zonas elevadas hasta lagos o costas. En ocasiones forman curvas amplias sobre una llanura. En otras atraviesan valles estrechos. Las islas, las bahías y los cabos también permiten reconocer una costa. Al observarlos juntos entendemos mejor por qué dos lugares cercanos pueden tener paisajes diferentes. La distancia en línea recta es solo una parte de la explicación: el terreno y los caminos disponibles también cuentan.

Finalmente, un mapa necesita orientación. Una pequeña referencia al norte suele bastar para situarnos. Si giramos la imagen durante una animación, es útil conservar alguna referencia reconocible. Los movimientos de cámara deben ayudar a encontrar el siguiente lugar, no distraer de la explicación. Una transición suave puede conectar una vista general con otra más cercana. Cuando el movimiento termina, conviene dar tiempo para reconocer lo que estamos viendo. Así, el mapa deja de ser un dibujo complicado y se convierte en una herramienta sencilla para observar, comparar y comprender el mundo que tenemos alrededor.

Prompt template and voice direction used for both tests

Synthesize single-speaker speech in Spanish for an educational historical documentary.
VOICE DIRECTION (not spoken):
Narrador masculino adulto Charon habitual de Geo en Corto. Español de España. Voz viva, curiosa, cercana y segura; cuenta una historia fascinante a un adulto, con energía natural y sin exageración teatral. Mantén exactamente el mismo timbre y registro durante toda la toma. Ritmo ágil con frases claras y pausas breves naturales; dale espacio a las preguntas y revelaciones sin silencios largos. No lectura monótona de libro, no voz triste, no solemnidad institucional ni tráiler. Énfasis selectivo en contrastes. No acelerar ni atropellar sílabas. Pronuncia completos los nombres históricos. Lee exactamente el texto, sin introducciones, sin omitir ni añadir palabras. Sin música ni efectos.
Read ONLY the following transcript, verbatim. No introduction, additions, or sound effects.
TRANSCRIPT:
[The short or long transcript above.]

Could you clarify:

  1. Does this particular SAFETY + incomplete-stream response indicate content filtering or a synthesis/backend failure?
  2. Is there a known issue or supported fix for longer single-speaker generation with this model?
  3. If the input is acceptable, is shorter chunking the supported remedy, or should we wait for a service fix?

We want to preserve the same voice and follow the supported approach, without weakening safety settings. No API keys, private account identifiers or documentary script are included. Thank you.

Send full code, prompt

Thanks for replying. Here is a minimal standalone version of the request code (Python standard library, REST/unary). No credentials or private project identifiers are included.

The complete 480-word neutral reproduction transcript is already in post #1 under “Independent neutral long transcript”. Save that exact text as neutral.txt (UTF-8) next to this script. The full voice direction and prompt construction are below. The key is read locally from an environment variable and is never printed.

import os, json, base64, wave, urllib.request
from pathlib import Path

model = "gemini-3.1-flash-tts-preview"
key = os.environ["GEMINI_API_KEY"].strip()
text = Path("neutral.txt").read_text(encoding="utf-8-sig").strip()
direction = (
    "Narrador masculino adulto Charon habitual de Geo en Corto. Español de España. "
    "Voz viva, curiosa, cercana y segura; cuenta una historia fascinante a un adulto, "
    "con energía natural y sin exageración teatral. Mantén exactamente el mismo "
    "timbre y registro durante toda la toma. Ritmo ágil con frases claras y pausas "
    "breves naturales; dale espacio a las preguntas y revelaciones sin silencios "
    "largos. No lectura monótona de libro, no voz triste, no solemnidad institucional "
    "ni tráiler. Énfasis selectivo en contrastes. No acelerar ni atropellar sílabas. "
    "Pronuncia completos los nombres históricos. Lee exactamente el texto, sin "
    "introducciones, sin omitir ni añadir palabras. Sin música ni efectos."
)
prompt = (
    "Synthesize single-speaker speech in Spanish for an educational historical documentary.\n"
    "VOICE DIRECTION (not spoken):\n" + direction +
    "\nRead ONLY the following transcript, verbatim. No introduction, additions, or sound effects."
    "\nTRANSCRIPT:\n" + text
)
payload = {
    "contents": [{"parts": [{"text": prompt}]}],
    "generationConfig": {
        "maxOutputTokens": 16384,
        "responseModalities": ["AUDIO"],
        "speechConfig": {
            "voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Charon"}}
        }
    }
}
request = urllib.request.Request(
    "https://generativelanguage.googleapis.com/v1beta/models/" + model + ":generateContent",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Content-Type": "application/json", "x-goog-api-key": key},
)
with urllib.request.urlopen(request, timeout=300) as response:
    result = json.load(response)
candidates = result.get("candidates", [])
candidate = candidates[0] if candidates else {}
print(json.dumps({
    "finishReason": candidate.get("finishReason"),
    "finishMessage": candidate.get("finishMessage"),
    "promptFeedback": result.get("promptFeedback"),
    "usageMetadata": result.get("usageMetadata"),
}, ensure_ascii=False, indent=2))
if candidate.get("finishReason") != "STOP":
    raise SystemExit("No complete audio; no automatic retry.")
chunks = []
for part in candidate.get("content", {}).get("parts", []):
    inline = part.get("inlineData", {})
    if inline:
        mime = inline.get("mimeType", "").lower()
        assert mime.startswith(("audio/l16", "audio/pcm")) and "rate=24000" in mime
        chunks.append(base64.b64decode(inline["data"], validate=True))
pcm = b"".join(chunks)
assert pcm and len(pcm) % 2 == 0
with wave.open("test.wav", "wb") as output:
    output.setnchannels(1)
    output.setsampwidth(2)
    output.setframerate(24000)
    output.writeframes(pcm)
print("Audio seconds:", len(pcm) / 48000)

Update from 29 October: two new, independent neutral texts succeeded with the same model, voice and request settings, producing 13.76 seconds and 54.8 seconds of audio. Longer documentary requests still returned SAFETY with “The audio stream could not be completed”, no audio and no HTTP 429. The earlier neutral 480-word test also failed, so we cannot conclude that historical subject matter is the cause, or that duration alone is the cause.

Could you clarify whether this specific response represents content filtering or a synthesis/backend failure? If the neutral input is acceptable, is shorter chunking the supported remedy for this model, or is there a service issue we should wait for? We do not want to weaken safety settings or keep making blind retries. Thank you.

Hello @Ruben_Alvarez1 ,

Null promptFeedback and safetyRatings indicate your Spanish script did not trigger an adjustable harm-category text filter, which already defaults to Off (Safety settings), so weakening safetySettings is not needed. gemini-3.1-flash-tts-preview is a legacy preview model scheduled for shutdown on November 17, 2026 (Deprecations).

Next steps:

  • Migrate to gemini-3.8-flash-tts (or gemini-3.8-flash-lite-tts for lower latency) for long single-speaker narration while keeping prebuilt voice "Charon" (Voice options).
  • Pass only the verbatim Spanish transcript in contents[0].parts[0].text and move short delivery cues into parts[0].speechMetadata.style (SpeechMetadata), omitting speaker names, demographic labels, and instructions to keep the same timbre (Consistency guide).
  • Update audio file writing for 3.8 TTS: unary generateContent returns complete audio/wav bytes with a RIFF header by default, so write the decoded bytes directly to .wav or set "responseFormat": {"audio": {"mimeType": "AUDIO_L16", "sampleRate": 24000}} in generationConfig (AudioResponseFormat) to keep raw 24 kHz PCM output.
  • For extended multi-minute scripts, split narration into shorter paragraph or section requests with the same voiceName and one short constant style string (Multi-turn generation).