Generación de texto a voz (TTS) con la API de Gemini


Puedes pedirle a un modelo de TTS de Gemini que genere una salida de voz (audio) a partir de una instrucción de texto. Cuando usas Firebase AI Logic, puedes realizar esta solicitud directamente desde tu app.

La generación de texto a voz (TTS) es controlable, lo que significa que proporcionas el texto exacto para sintetizarlo en voz. También puedes usar lenguaje natural en tus instrucciones para guiar el estilo, el acento, el ritmo y el tono de la salida de audio. Puedes pensar en TTS como lo opuesto a la transcripción (voz a texto).

Esta función está disponible con cualquiera de los modelos Gemini -tts, que están optimizados para la generación de voz de alta calidad y baja latencia.

Con esta función, puedes hacer lo siguiente:

  • Narración interactiva: Crea audiolibros o juegos de rol envolventes en los que el modelo cambie de voz para diferentes personajes o adapte su tono (como susurrar en suspenso o reírse de un chiste) para que coincida con la narrativa.

  • Aprendizaje de idiomas: Crea guías de pronunciación que puedan leer texto con acentos regionales específicos o a ritmos más lentos para ayudar a los estudiantes a practicar pronunciaciones difíciles.

  • Lectores de contenido adaptados al contexto: Lee artículos de noticias, recetas o entradas de blog en voz alta con una voz y un tono emocional que coincidan con el contenido (como un tono serio para las noticias de último momento o un tono cálido y paciente para las instrucciones de cocina paso a paso).

En esta guía, se muestra cómo generar voz a partir de una entrada de texto con uno o varios interlocutores y cómo transmitir la respuesta de audio.

Ir al código para un solo interlocutor Ir al código para varios interlocutores Ir al código para respuestas transmitidas

Comparación entre TTS y Live API

Tanto los modelos de texto a voz (TTS) como los de Live API son modelos de baja latencia que generan voz y que se pueden configurar para diferentes idiomas y voces de respuesta. Sin embargo, se usan en casos muy diferentes.

  • La generación de texto a voz (TTS) es una interacción unidireccional de solicitud y respuesta (entrada de texto, salida de audio). Está adaptado para situaciones que requieren una recitación exacta del texto proporcionado con un control detallado del estilo y el sonido, como la narración de podcasts, audiolibros o la lectura de artículos en voz alta.

  • La generación Live API admite la transmisión bidireccional para conversaciones de voz en tiempo real (entrada y salida de voz). Se destaca en contextos conversacionales dinámicos en los que el modelo decide el discurso aplicable que se debe mostrar. Ten en cuenta que los modelos de Live API más recientes también admiten entradas de video y de imagen.

Antes de comenzar

Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página.

Si aún no lo hiciste, completa la guía de introducción, en la que se describe cómo configurar tu proyecto de Firebase, conectar tu app a Firebase, agregar el SDK, inicializar el servicio de backend para el proveedor de Gemini API que elijas y crear una instancia de GenerativeModel.

Para probar y, luego, iterar tus instrucciones, te recomendamos usar Google AI Studio.

Modelos que admiten esta función

  • gemini-3.1-flash-tts-preview

Generar voz a partir de texto

Puedes generar voz a partir del texto proporcionado con un modelo de TTS de Gemini.

Genera voz con un solo interlocutor

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas el contenido específico del proveedor en esta página.

Puedes configurar el modelo para que genere audio con una sola voz.

En tu GenerationConfig, incluye lo siguiente:

Llama a generateContent con tu instrucción de texto. El modelo devuelve datos de audio PCM sin procesar en las partes de la respuesta.

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
let config = GenerationConfig(
  responseModalities: [.audio],
  speechConfig: SpeechConfig(voiceName: "Kore", languageCode: "en-US")
)

// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
  modelName: "gemini-3.1-flash-tts-preview",
  generationConfig: config
)

// Provide a text prompt.
let prompt = "Say cheerfully: Have a wonderful day!"

// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
  let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
  let mimeType = part.mimeType  // for example: "audio/pcm"
  print("Received audio data with MIME type: \(mimeType)")

  // To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
  playRawPcm(data: data)
}

Kotlin

En Kotlin, los métodos de este SDK son funciones de suspensión y se deben llamar desde un alcance de corrutina.

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
val config = generationConfig {
    responseModalities = listOf(ResponseModality.AUDIO)
    speechConfig = SpeechConfig(
        voice = Voice("Kore"),
        languageCode = "en-US"
    )
}

// Initialize the Gemini Developer API backend service.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
    .generativeModel(
        modelName = "gemini-3.1-flash-tts-preview",
        generationConfig = config
    )

// Provide a text prompt.
val prompt = "Say cheerfully: Have a wonderful day!"

// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
    val pcmData = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    val mimeType = part.mimeType   // for example: "audio/pcm"

    // To play back PCM audio data, you'll need to write your own `playAudio` function.
    playAudio(pcmData)
}

Java

En Java, los métodos de transmisión de este SDK devuelven un tipo Publisher de la biblioteca de Reactive Streams.

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
    .setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
    .setSpeechConfig(new SpeechConfig(new Voice("Kore"), "en-US"))
    .build();

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-3.1-flash-tts-preview", config);

// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt.
String prompt = "Say cheerfully: Have a wonderful day!";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();

// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        Part part = result.getCandidates().get(0).getContent().getParts().get(0);
        if (part instanceof InlineDataPart) {
            byte[] pcmData = ((InlineDataPart) part).getInlineData();
            String mimeType = ((InlineDataPart) part).getMimeType();

            // To play back PCM audio data, you'll need to write your own `playAudio` function.
            playAudio(pcmData);
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } },
    languageCode: "en-US"
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

// Provide a text prompt.
const prompt = "Say cheerfully: Have a wonderful day!";

// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();

// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
  const pcmBase64 = inlineDataParts[0].inlineData.data;
  // Decode base64 to ArrayBuffer
  const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

  // To play back a PCM buffer, you'll need to write your own `playAudio` function.
  playAudio(pcmBuffer);
}

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
  responseModalities: [ResponseModalities.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'gemini-3.1-flash-tts-preview',
  generationConfig: config,
);

// Provide a text prompt.
final prompt = 'Say cheerfully: Have a wonderful day!';

// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);

// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
  final Uint8List pcmData = part.bytes;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)

  // To play back PCM audio data, you'll need to write your own `playAudio` function.
  await playAudio(pcmData);
}

Unity


using Firebase.AI;

// Set `responseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name and language code.
var config = new GenerationConfig(
  responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
  speechConfig: SpeechConfig.UsePrebuiltVoice("Kore", "en-US")
);

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
  modelName: "gemini-3.1-flash-tts-preview",
  generationConfig: config
);

// Provide a text prompt.
var prompt = "Say cheerfully: Have a wonderful day!";

// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);

// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
  foreach (var part in response.Candidates[0].Content.Parts) {
    if (part is ModelContent.InlineDataPart inlineData) {
      byte[] pcmData = inlineData.Data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)

      // To play back PCM audio data, you'll need to write your own `playAudio` function.
      playAudio(pcmData);
    }
  }
}

Genera voz con varios interlocutores

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas el contenido específico del proveedor en esta página.

Puedes configurar el modelo para que use diferentes voces para los distintos interlocutores en el texto. Esto es útil para generar audio para diálogos o conversaciones.

  1. Crea un MultiSpeakerVoiceConfig que asigne nombres de interlocutores (que usarás en tu instrucción) a nombres de voces de respuesta específicos (por ejemplo, Kore).

    La configuración de varios interlocutores admite exactamente 2 interlocutores.

  2. En tu GenerationConfig, incluye lo siguiente:

    • Configura responseModalities para que incluya AUDIO.

    • Configura un SpeechConfig con lo siguiente:

  3. En tu instrucción, indica quién habla usando los nombres de los interlocutores como prefijos (por ejemplo, Joe: Hello. Jane: Hi.).

Llama a generateContent con tu instrucción de texto. El modelo devuelve datos de audio PCM sin procesar en las partes de la respuesta.

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
let multiSpeechConfig = SpeechConfig(
  multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
    speakerVoiceConfigs: [
      SpeakerVoiceConfig(speaker: "Joe", voiceName: "Puck"),
      SpeakerVoiceConfig(speaker: "Jane", voiceName: "Kore")
    ]
  ),
  languageCode: "en-US"
)

// Set `responseModalities` to include `audio`.
let config = GenerationConfig(
  responseModalities: [.audio],
  speechConfig: multiSpeechConfig
)

// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
  modelName: "gemini-3.1-flash-tts-preview",
  generationConfig: config
)

// Provide a text prompt that includes the names of the speakers.
let prompt = """
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
"""

// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
  let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
  let mimeType = part.mimeType  // for example: "audio/pcm"
  print("Received audio data with MIME type: \(mimeType)")

  // To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
  playRawPcm(data: data)
}

Kotlin

En Kotlin, los métodos de este SDK son funciones de suspensión y se deben llamar desde un alcance de corrutina.

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
val multiSpeechConfig = SpeechConfig(
    multiSpeakerVoiceConfig = MultiSpeakerVoiceConfig(
        speakerVoiceConfigs = listOf(
            SpeakerVoiceConfig(speaker = "Joe", voice = Voice("Puck")),
            SpeakerVoiceConfig(speaker = "Jane", voice = Voice("Kore"))
        )
    ),
    languageCode = "en-US"
)

// Set `responseModalities` to include `AUDIO`.
val config = generationConfig {
    responseModalities = listOf(ResponseModality.AUDIO)
    speechConfig = multiSpeechConfig
}

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
    .generativeModel(
        modelName = "gemini-3.1-flash-tts-preview",
        generationConfig = config
    )

// Provide a text prompt that includes the names of the speakers.
val prompt = """
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
"""

// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
    val pcmData = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    val mimeType = part.mimeType   // for example: "audio/pcm"

    // To play back PCM audio data, you'll need to write your own `playAudio` function.
    playAudio(pcmData)
}

Java

En Java, los métodos de transmisión de este SDK devuelven un tipo Publisher de la biblioteca de Reactive Streams.

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
MultiSpeakerVoiceConfig multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
    Arrays.asList(
        new SpeakerVoiceConfig("Joe", new Voice("Puck")),
        new SpeakerVoiceConfig("Jane", new Voice("Kore"))
    )
);

SpeechConfig multiSpeechConfig = new SpeechConfig(multiSpeakerVoiceConfig);

// Set `responseModalities` to include `AUDIO`.
GenerationConfig config = new GenerationConfig.Builder()
    .setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
    .setSpeechConfig(multiSpeechConfig)
    .build();

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
         .generativeModel("gemini-3.1-flash-tts-preview", config);

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt that includes the names of the speakers.
String prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();

// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        Part part = result.getCandidates().get(0).getContent().getParts().get(0);
        if (part instanceof InlineDataPart) {
            byte[] pcmData = ((InlineDataPart) part).getInlineData();  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
            String mimeType = ((InlineDataPart) part).getMimeType();   // for example: "audio/pcm"

            // To play back PCM audio data, you'll need to write your own `playAudio` function.
            playAudio(pcmData);
        }
    }

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    multiSpeakerVoiceConfig: {
      speakerVoiceConfigs: [
        { speaker: "Joe", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Puck" } } },
        { speaker: "Jane", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
      ]
    },
    languageCode: "en-US"
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

// Provide a text prompt that includes the names of the speakers.
const prompt = `
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
`;

// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();

// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
  const pcmBase64 = inlineDataParts[0].inlineData.data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
  const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

  // To play back a PCM buffer, you'll need to write your own `playAudio` function.
  playAudio(pcmBuffer);
}

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
final multiSpeechConfig = SpeechConfig.multiSpeaker(
  multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
    speakerVoiceConfigs: [
      SpeakerVoiceConfig(speaker: 'Joe', voiceName: 'Puck'),
      SpeakerVoiceConfig(speaker: 'Jane', voiceName: 'Kore'),
    ],
  ),
  languageCode: 'en-US',
);

// Set `responseModalities` to include `audio`.
final config = GenerationConfig(
  responseModalities: [ResponseModalities.audio],
  speechConfig: multiSpeechConfig,
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'gemini-3.1-flash-tts-preview',
  generationConfig: config,
);

// Provide a text prompt that includes the names of the speakers.
final prompt = '''
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
''';

// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);

// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
  final Uint8List pcmData = part.bytes;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)

  // To play back PCM audio data, you'll need to write your own `playAudio` function.
  await playAudio(pcmData);
}

Unity


using Firebase.AI;

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
var multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
  new System.Collections.Generic.List<SpeakerVoiceConfig> {
    SpeakerVoiceConfig.UsePrebuiltVoice("Joe", "Puck"),
    SpeakerVoiceConfig.UsePrebuiltVoice("Jane", "Kore")
  }
);

var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);

// Set `responseModalities` to include `Audio`.
var config = new GenerationConfig(
  responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
  speechConfig: multiSpeechConfig
);

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
  modelName: "gemini-3.1-flash-tts-preview",
  generationConfig: config
);

// Provide a text prompt that includes the names of the speakers.
var prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";

// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);

// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
  foreach (var part in response.Candidates[0].Content.Parts) {
    if (part is ModelContent.InlineDataPart inlineData) {
      byte[] pcmData = inlineData.Data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)

      // To play back PCM audio data, you'll need to write your own `playAudio` function.
      playAudio(pcmData);
    }
  }
}

Transmite la respuesta

Antes de probar esta muestra, completa la sección Antes de comenzar de esta guía para configurar tu proyecto y tu app.
En esa sección, también harás clic en un botón para el proveedor de Gemini API que elijas, de modo que veas el contenido específico del proveedor en esta página.

Puedes lograr interacciones más rápidas y una latencia más baja transmitiendo la respuesta de audio a medida que se genera, en lugar de esperar a que se complete todo el archivo de audio.

La transmisión de voz generada es compatible con las configuraciones de un solo interlocutor y de varios interlocutores. Solo se admite cuando se usan los modelos de Gemini 3.x TTS.

Para transmitir la respuesta de voz, llama a generateContentStream en lugar de generateContent y controla los fragmentos a medida que llegan. En los siguientes ejemplos, se muestra cómo transmitir una respuesta de un solo interlocutor:

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
let config = GenerationConfig(
  responseModalities: [.audio],
  speechConfig: SpeechConfig(voiceName: "Kore")
)

// Create a `GenerativeModel` instance with a model that supports speech generation.
let model = ai.generativeModel(
  modelName: "gemini-3.1-flash-tts-preview",
  generationConfig: config
)

// Provide a text prompt.
let prompt = "Tell me a story about a brave knight."

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
let responseStream = try model.generateContentStream(prompt)

// Extract the audio data and handle it for downstream use. For example:
for try await chunk in responseStream {
  for part in chunk.inlineDataParts {
    let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
    let mimeType = part.mimeType  // for example: "audio/pcm"

    // Append the audio chunk to your audio queue/buffer for playback.
    appendAudioChunk(data)
  }
}

Kotlin

En Kotlin, los métodos de este SDK son funciones de suspensión y se deben llamar desde un alcance de corrutina.

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
val config = generationConfig {
    responseModalities = listOf(ResponseModality.AUDIO)
    speechConfig = SpeechConfig(voice = Voice("Kore"))
}

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
    .generativeModel(
        modelName = "gemini-3.1-flash-tts-preview",
        generationConfig = config
    )

// Provide a text prompt.
val prompt = "Tell me a story about a brave knight."

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
// Extract the audio data and handle it for downstream use.
model.generateContentStream(prompt).collect { chunk ->
    val part = chunk.candidates.firstOrNull()?.content?.parts?.firstOrNull()
    if (part is InlineDataPart) {
        val pcmChunk = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
        val mimeType = part.mimeType    // for example: "audio/pcm"

        // Append the audio chunk to your audio queue/buffer for playback.
        appendAudioChunk(pcmChunk)
    }
}

Java

En Java, los métodos de transmisión de este SDK devuelven un tipo Publisher de la biblioteca de Reactive Streams.

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
    .setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
    .setSpeechConfig(new SpeechConfig(new Voice("Kore")))
    .build();

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
        .generativeModel("gemini-3.1-flash-tts-preview", config);

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt.
String prompt = "Tell me a story about a brave knight.";
Content content = new Content.Builder().addText(prompt).build();

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
Publisher<GenerateContentResponse> streamingResponse =
    model.generateContentStream(content);

// Extract the audio data and handle it for downstream use.
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
  @Override
  public void onSubscribe(Subscription s) {
      s.request(Long.MAX_VALUE);
  }

  @Override
  public void onNext(GenerateContentResponse chunk) {
      Part part = chunk.getCandidates().get(0).getContent().getParts().get(0);
      if (part instanceof InlineDataPart) {
          byte[] pcmChunk = ((InlineDataPart) part).getInlineData();  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
          String mimeType = ((InlineDataPart) part).getMimeType();    // for example: "audio/pcm"

          // Append the audio chunk to your audio queue/buffer for playback.
          appendAudioChunk(pcmChunk);
      }
  }

  @Override
  public void onComplete() {
      // Audio stream complete.
  }

  @Override
  public void onError(Throwable t) {
      t.printStackTrace();
  }
});

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } }
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

// Provide a text prompt.
const prompt = "Tell me a story about a brave knight.";

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
const result = await model.generateContentStream(prompt);

// Extract the audio data and handle it for downstream use. For example:
const playbackQueue = [];
for await (const chunk of result.stream) {
  const inlineDataParts = chunk.inlineDataParts();
  if (inlineDataParts?.[0]) {
    const pcmBase64 = inlineDataParts[0].inlineData.data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

    // Append the audio chunk to your audio queue/buffer for playback.
    playbackQueue.push(pcmBuffer);
  }
}

// To play back an array of PCM buffers in sequence, you'll need to write your own `processPlaybackQueue` function.
processPlaybackQueue(playbackQueue);

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
  responseModalities: [ResponseModalities.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore'),
);

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'gemini-3.1-flash-tts-preview',
  generationConfig: config,
);

// Provide a text prompt.
final prompt = 'Tell me a story about a brave knight.';

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
final responseStream = model.generateContentStream([Content.text(prompt)]);

// Extract the audio data and handle it for downstream use. For example:
await for (final chunk in responseStream) {
  final part = chunk.candidates.first.content.parts.first;
  if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
    final Uint8List pcmChunk = part.bytes;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)

    // Append the audio chunk to your audio queue/buffer for playback.
    appendAudioChunk(pcmChunk);
  }
}

Unity


using System.Collections.Generic;
using System.Linq;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Set `ResponseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
var config = new GenerationConfig(
    responseModalities: new List<ResponseModality> { ResponseModality.Audio },
    speechConfig: SpeechConfig.UsePrebuiltVoice("Kore")
);

// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
    modelName: "gemini-3.1-flash-tts-preview",
    generationConfig: config
);

// Provide a text prompt.
var prompt = "Tell me a story about a brave knight.";

// Call `GenerateContentStreamAsync` to generate the speech output stream based on your text prompt.
var responseStream = model.GenerateContentStreamAsync(prompt);

// Extract the audio data and handle it for downstream use. For example:
await foreach (var response in responseStream)
{
    var audioParts = response.Candidates.FirstOrDefault().Content.Parts
                            .OfType<ModelContent.InlineDataPart>();

    foreach (var part in audioParts)
    {
        byte[] pcmChunk = part.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)

        // Append the audio chunk to your audio queue/buffer for playback.
        appendAudioChunk(pcmChunk);
    }
}



Controla la respuesta hablada con instrucciones

Puedes influir en el tono, el ritmo y el estilo de la voz generada con técnicas de instrucciones específicas.

En las siguientes subsecciones sobre la estructura de las instrucciones y las etiquetas de audio, se describen lineamientos de alto nivel. Para obtener orientación detallada, consulta esta guía de instrucciones.

Estructura de las instrucciones

Para obtener los mejores resultados, estructura tu instrucción con los siguientes componentes:

  • Audio Profile: Describe la personalidad, la identidad principal y el arquetipo del interlocutor (por ejemplo, A warm, professional narrator).

  • Scene: Describe el entorno y la vibra emocional (por ejemplo, In a quiet library o Amidst a noisy crowd).

  • Director's Notes: Describe la emoción, el ritmo, el estilo y el acento (por ejemplo, Speak slowly and with mystery).

  • Sample Context: Proporciona un punto de partida para el modelo (por ejemplo, The speaker is greeting a close friend).

  • Transcripción: Es el texto real que se pronunciará. Para obtener el mejor rendimiento, asegúrate de que el tono y el contexto escritos del texto se alineen con el perfil de voz y las notas de dirección.

Instrucción de ejemplo:

[Audio Profile: A young, energetic voice]
[Scene: A lively sports broadcast]
[Director's Notes: Speak fast, with high energy and excitement]
[Sample Context: The game just ended with a last-second touchdown]
Welcome back fans! What an incredible game we're witnessing today!

Etiquetas de audio

Puedes insertar etiquetas de formato directamente en tu instrucción de texto para guiar el rendimiento del modelo.

Las etiquetas de audio solo se admiten cuando se usan los modelos Gemini 3.x TTS.

Entre las etiquetas de uso frecuente, se incluyen las siguientes:

  • [whispers]: Hablar en voz baja
  • [laughs]: Para agregar risas
  • [giggles]: Para agregar risas
  • [sighs]: Para agregar un suspiro
  • [gasp]: Para agregar un jadeo
  • [shouting]: Gritar
  • [excited]: Hablar con entusiasmo
  • [serious]: Hablar con seriedad
  • [sighs whispers]: Emociones combinadas (puedes combinar etiquetas)

Ten en cuenta lo siguiente cuando uses etiquetas de audio:

  • No hay una lista exhaustiva: No hay una lista fija de etiquetas admitidas. Puedes experimentar con diferentes emociones y expresiones (como [bored], [sarcastically] o incluso [like dracula]) para ver cómo cambia el resultado.

  • Instrucción de texto que no está en inglés: Si tu instrucción de texto no está en inglés, debes usar etiquetas de audio en inglés para obtener mejores resultados.

Instrucción de ejemplo:

I have a secret to tell you. [whispers] I found the hidden treasure. [laughs] I can't believe it!



Limitaciones y requisitos

Ten en cuenta las siguientes limitaciones y requisitos cuando uses la generación de voz:

  • La configuración de varios interlocutores admite exactamente 2 interlocutores.

  • Las siguientes funciones solo se admiten cuando se usan los modelos Gemini 3.x TTS: transmisión, etiquetas de audio y otros idiomas detectados automáticamente.

Restricciones para gemini-3.1-flash-tts-preview

  • Incoherencia de voz: Es posible que el resultado del modelo no siempre coincida de forma estricta con el interlocutor seleccionado si el tono y el contexto de la instrucción no se alinean con el perfil del interlocutor (por ejemplo, una voz masculina profunda que intenta hablar como una niña). Asegúrate de que el contexto de la instrucción coincida con la voz.
  • Resultados más largos: La calidad y la coherencia de la voz pueden variar en el caso de audios que duren más de unos minutos. Te recomendamos dividir las instrucciones de texto largas en partes más pequeñas.
  • Devoluciones ocasionales de tokens de texto: En ocasiones, el modelo devuelve tokens de texto en lugar de tokens de audio, lo que hace que la solicitud falle con un error 500. Debido a que esto ocurre de forma aleatoria en un pequeño porcentaje de solicitudes, debes implementar la lógica de reintento en tu app.
  • Rechazos falsos del clasificador: Las instrucciones vagas pueden hacer que falle el clasificador de síntesis de voz, lo que genera una solicitud rechazada (PROHIBITED_CONTENT) o hace que el modelo lea tus instrucciones de estilo en voz alta. Para evitarlo, usa una instrucción estructurada con un preámbulo claro (como Audio Profile y Director's Notes) al principio de la instrucción.



Idiomas y voces compatibles

Los modelos de TTS de Gemini toman una entrada de texto y generan una salida de audio, por lo que la respuesta es el habla sintetizada en sí. En las siguientes subsecciones, se enumeran las voces y los idiomas admitidos que los modelos de TTS de Gemini pueden "hablar" (o en los que pueden responder).

Las voces son multilingües, lo que significa que puedes usar la misma voz para generar voz en cualquiera de los idiomas admitidos. Por ejemplo, puedes configurar la voz en Kore y enviar un conjunto de instrucciones de texto en español, hindi y vietnamita. Todas las respuestas se darán con la voz de Kore, pero en cada uno de esos idiomas diferentes.

Nombres de las voces

Los modelos de TTS de Gemini admiten 30 voces en HD sintetizadas diferentes, cada una con características distintas. Puedes ver una lista de opciones de voces de respuesta y escuchar demostraciones de cada una expandiendo la sección que aparece a continuación.

Idiomas

Los modelos de TTS de Gemini pueden detectar automáticamente los siguientes idiomas en tu instrucción de texto. La voz generada estará en ese idioma.

Ten en cuenta que, de manera opcional, puedes establecer de forma explícita un código de idioma en la configuración de voz.

Idiomas compatibles con todos los modelos de generación de audio
Idioma Código BCP-47 Idioma Código BCP-47
Árabe (Egipto) ar-EG Alemán (Alemania) de-DE
Inglés (EE.UU.) en-US Español (EE.UU.) es-US
Francés (Francia) fr-FR Hindi (India) hi-IN
Indonesio (Indonesia) id-ID Italiano (Italia) it-IT
Japonés (Japón) ja-JP Coreano (Corea) ko-KR
Portugués (Brasil) pt-BR Ruso (Rusia) ru-RU
Holandés (Países Bajos) nl-NL Polaco (Polonia) pl-PL
Tailandés (Tailandia) th-TH Turco (Türkiye) tr-TR
Vietnamita (Vietnam) vi-VN Rumano (Rumania) ro-RO
Ucraniano (Ucrania) uk-UA Bengalí (Bangladés) bn-BD
Inglés (India) Paquete en-IN y hi-IN Maratí (India) mr-IN
Tamil (India) ta-IN Telugu (India) te-IN
Idiomas adicionales compatibles con los modelos 3.x que generan audio
Idioma Código BCP-47 Idioma Código BCP-47
Afrikaans af Filipino fil
Albanés sq Finlandés fi
Amárico am Gallego gl
Armenio hy Georgiano ka
Azerbaiyano az Griego el
Vasco eu Guyaratí gu
Bielorruso be Criollo haitiano ht
Búlgaro bg Hebreo he
Birmano my Húngaro hu
Catalán ca Islandés es
Cebuano ceb Javanés jv
Chino (mandarín) cmn Canarés kn
Croata h Konkani kok
Checo cs Laosiano lo
Danés da Latín la
Estonio et Letón lv
Lituano lt Luxemburgués lb
Macedonio mk Maithili mai
Malgache mg Malayo ms
Malayalam ml Mongol mn
Nepalí ne Noruego (bokmål) nb
Noruego (nynorsk) nn Oriya o
Pastún ps Persa fa
Punyabí pa Serbio sr
Sindhi sd Cingalés si
Eslovaco sk Esloveno sl
Suajili sw Sueco sv
Urdu ur

(Opcional) Establece un código de idioma de forma explícita

Si no especificas un código de idioma en la configuración de voz, el modelo detecta automáticamente el idioma en tu instrucción de texto.

Sin embargo, puedes configurar el idioma de forma explícita (con el parámetro languageCode en la configuración de voz). Para ello, debes usar uno de los siguientes códigos de configuración regional BCP-47 admitidos:

  • Árabe: ar-XA
  • Bengalí: bn-IN
  • Chino (mandarín): cmn-CN
  • Neerlandés: nl-NL
  • Inglés: en-US, en-GB, en-AU, en-IN
  • Francés: fr-FR, fr-CA
  • Alemán: de-DE
  • Guyaratí: gu-IN
  • Hindi: hi-IN
  • Indonesio: id-ID
  • Italiano: it-IT
  • Japonés: ja-JP
  • Canarés: kn-IN
  • Coreano: ko-KR
  • Malabar: ml-IN
  • Maratí: mr-IN
  • Polaco: pl-PL
  • Portugués: pt-BR
  • Ruso: ru-RU
  • Español: es-US, es-ES
  • Tamil: ta-IN
  • Télugu: te-IN
  • Tailandés: th-TH
  • Turco: tr-TR
  • Vietnamita: vi-VN



¿Qué más puedes hacer?

Prueba otras funciones

Aprende a controlar la generación de contenido

También puedes experimentar con instrucciones y configuraciones de modelos, y hasta obtener un fragmento de código generado con Google AI Studio.

Más información sobre los modelos compatibles

Obtén información sobre los modelos disponibles para varios casos de uso, sus cuotas y sus precios.


Envía comentarios sobre tu experiencia con Firebase AI Logic