Puedes pedirle a un modelo de Gemini TTS 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. Además, puedes usar lenguaje natural en tus instrucciones para guiar el estilo, el acento, el ritmo y el tono de la salida de audio. Puedes considerar el 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 capacidad, puedes hacer lo siguiente:
Narración interactiva: Crea audiolibros o juegos de rol envolventes en los que el modelo cambia de voz para diferentes personajes o adapta su tono (como susurrar en suspenso o reírse de un chiste) para que coincida con la narración.
Aprendizaje de idiomas: Crea guías de pronunciación que puedan leer texto con acentos regionales específicos o a un ritmo más lento para ayudar a los estudiantes a practicar pronunciaciones difíciles.
Lectores de contenido sensibles al contexto: Leen en voz alta artículos de noticias, recetas o entradas de blog con una voz y un tono emocional que coinciden con el contenido (por ejemplo, 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 orador Ir al código para varios oradores Ir al código para respuestas transmitidas
Comparación entre el TTS y el Live API
Tanto los modelos de texto a voz (TTS) como los modelos de Live API son modelos de baja latencia que generan voz y se pueden configurar para diferentes voces y lenguajes de respuesta. Sin embargo, cumplen casos de uso muy diferentes.
La generación de texto a voz (TTS) es una interacción unidireccional de solicitud y respuesta (texto como entrada y audio como salida). Está diseñado para situaciones que requieren una recitación exacta del texto proporcionado con un control detallado sobre el estilo y el sonido, como la narración de podcasts, audiolibros o la lectura de artículos en voz alta.
La generación de Live API admite la transmisión bidireccional para las conversaciones de voz en tiempo real (voz entrante y saliente). Se destaca en contextos conversacionales dinámicos en los que el modelo decide el discurso aplicable que debe devolver. Ten en cuenta que los modelos Live API más recientes también admiten entradas de imágenes y videos.
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 has hecho, 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 capacidad
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 Gemini.
Genera voz con un solo orador
|
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 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:
Establece
responseModalitiespara incluirAUDIO.Configura un
SpeechConfigcon lo siguiente:(Obligatorio) Nombre de la voz de respuesta (por ejemplo,
Kore)(Opcional) Código de idioma.
Si no especificas un idioma, los modelos de Gemini de TTS pueden detectar automáticamente el idioma en la instrucción.
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 deben llamarse 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 tipoPublisher 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: [ResponseModality.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',
config: 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 oradores
|
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 contenido específico del proveedor en esta página. |
Puedes configurar el modelo para que use diferentes voces para los distintos interlocutores del texto. Esto es útil para generar audio para diálogos o conversaciones.
Crea un
MultiSpeakerVoiceConfigque asigne nombres de oradores (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.
En tu
GenerationConfig, incluye lo siguiente:Establece
responseModalitiespara incluirAUDIO.Configura un
SpeechConfigcon lo siguiente:(Obligatorio) Pasa tu
MultiSpeakerVoiceConfig.(Opcional) Código de idioma.
Si no especificas un idioma, los modelos de Gemini de TTS pueden detectar automáticamente el idioma en la instrucción.
En tu instrucción, indica quién está hablando usando los nombres de los oradores 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 deben llamarse 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 tipoPublisher 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: [ResponseModality.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',
config: 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 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 se admite para las configuraciones de un solo orador y varios oradores. Solo se admite cuando se usan los modelos 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 orador:
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 deben llamarse 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 tipoPublisher 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: [ResponseModality.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',
config: 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 del discurso generado con técnicas de instrucción específicas.
En las siguientes subsecciones sobre la estructura de la instrucción y las etiquetas de audio, se describe la orientación 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 el arquetipo, la identidad principal y el personaje del orador (por ejemplo,A warm, professional narrator).Scene: Describe el entorno y el ambiente emocional (por ejemplo,In a quiet libraryoAmidst 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 al 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 del texto escrito coincidan 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.
Las etiquetas de uso frecuente incluyen las siguientes:
[whispers]: Para hablar en voz baja[laughs]: Para agregar risas[giggles]: Para agregar risas[sighs]: Para agregar un suspiro[gasp]: Para agregar un jadeo[shouting]: Para gritar[excited]: Hablar con entusiasmo[serious]: Hablar en serio[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 compatibles. 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 en un idioma distinto del 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
- Inconsistencia de voz: Es posible que el resultado del modelo no siempre coincida estrictamente con el orador seleccionado si el tono y el contexto de tu instrucción no se alinean con el perfil del orador (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.
- Salidas más largas: La calidad y la coherencia del habla pueden variar en el caso de audios de más de unos minutos. Te recomendamos que dividas las instrucciones de texto largas en fragmentos más pequeños.
- Devoluciones ocasionales de tokens de texto: En ocasiones, el modelo devuelve tokens de texto en lugar de tokens de audio, lo que provoca que la solicitud falle con un error
500. Dado que esto ocurre de forma aleatoria en un pequeño porcentaje de solicitudes, debes implementar una lógica de reintento en tu app. - Rechazos falsos del clasificador: Las instrucciones vagas pueden fallar en el clasificador de síntesis de voz, lo que genera una solicitud rechazada (
PROHIBITED_CONTENT) o hace que el modelo lea en voz alta tus instrucciones de estilo. Para evitar esto, usa una instrucción estructurada con un preámbulo claro (comoAudio ProfileyDirector's Notes) al comienzo de la instrucción.
Idiomas y voces compatibles
Los modelos de TTS Gemini toman texto como entrada y generan 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 compatibles con los que pueden "hablar" (o responder) los modelos de Gemini TTS.
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 serán con la voz de Kore, pero en cada uno de esos idiomas diferentes.
Nombres de las voces
Los modelos de Gemini TTS admiten 30 voces en HD sintetizadas diferentes, cada una con características distintivas. Puedes ver una lista de las opciones de voz de respuesta y escuchar demostraciones de cada voz expandiendo la siguiente sección.
Idiomas
Los modelos de Gemini TTS pueden detectar automáticamente los siguientes idiomas en tu instrucción de texto. El discurso generado estará en ese idioma.
Ten en cuenta que, de manera opcional, puedes establecer explícitamente 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 hi-IN y en-IN | Maratí (India) | mr-IN |
| Tamil (India) | ta-IN | Telugu (India) | te-IN |
Idiomas adicionales admitidos por los modelos de generación de audio 3.x
| 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 de forma explícita un código de idioma
Si no especificas un código de idioma en la configuración de voz, el modelo detectará automáticamente el idioma en la instrucción de texto.
Sin embargo, puedes establecer 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 compatibles:
- Árabe:
ar-XA - Bengalí:
bn-IN - Chino (mandarín):
cmn-CN - Holandé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 - Malayalam:
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?
- Aprende a contar tokens antes de enviar instrucciones largas al modelo.
-
Comienza a pensar en la preparación para la producción (consulta la lista de tareas de producción):
- Aplica Firebase App Check lo antes posible para ayudar a proteger Gemini API contra el abuso de clientes no autorizados.
- Usa Firebase Remote Config o plantillas de instrucciones del servidor para que puedas realizar cambios a pedido en la configuración de tu función basada en IA (como el nombre del modelo) sin lanzar una nueva versión de tu app.
Prueba otras capacidades
- Crea conversaciones de varios turnos (chat).
- Generar texto a partir de instrucciones solo de texto
- Genera resultados estructurados (como JSON) a partir de instrucciones tanto de texto como multimodales.
- Generar y editar imágenes a partir de instrucciones de texto y multimodales
- Transmite entrada y salida (incluido el audio) con Gemini Live API.
-
Usa herramientas (como llamadas a funciones y fundamentación con
Google Search oGoogle Maps ) para conectar un modelo Gemini a otras partes de tu app y a sistemas e información externos.
Más información para controlar la generación de contenido
- Comprende el diseño de instrucciones, incluidas las prácticas recomendadas, las estrategias y los ejemplos de instrucciones.
- Configura los parámetros del modelo, como la cantidad máxima de tokens de salida, la probabilidad de tokens de salida repetidos, etcétera.
- Usa la configuración de seguridad para ajustar la probabilidad de obtener respuestas que se puedan considerar dañinas.
Más información sobre los modelos compatibles
Obtén información sobre los modelos disponibles para diversos casos de uso, sus cuotas y sus precios.Envía comentarios sobre tu experiencia con Firebase AI Logic