Generazione di sintesi vocale (TTS) utilizzando l'API Gemini


Puoi chiedere a un modello TTS Gemini di generare un output vocale (audio) da un prompt testuale. Quando utilizzi Firebase AI Logic, puoi effettuare questa richiesta direttamente dalla tua app.

La generazione di sintesi vocale (TTS) è controllabile, il che significa che fornisci il testo esatto da sintetizzare in voce. Inoltre, puoi utilizzare un linguaggio naturale nei prompt per definire lo stile, l'accento, il ritmo e il tono dell'uscita audio. Puoi pensare alla sintesi vocale come all'opposto della trascrizione (speech-to-text).

Questa funzionalità è disponibile utilizzando uno qualsiasi dei modelli Gemini -tts, che sono ottimizzati per la generazione di voce di alta qualità e a bassa latenza.

Con questa funzionalità puoi:

  • Narrazione interattiva: crea audiolibri coinvolgenti o giochi di ruolo in cui il modello cambia voce per personaggi diversi o adatta il tono (ad esempio sussurrando in caso di suspense o ridendo a una battuta) per adattarsi alla narrazione.

  • Apprendimento delle lingue: crea guide alla pronuncia che possono leggere il testo con accenti regionali specifici o a velocità più lente per aiutare gli studenti a esercitarsi con pronunce difficili.

  • Lettori di contenuti sensibili al contesto: leggi ad alta voce articoli di notizie, ricette o post di blog utilizzando una voce e un tono emotivo che corrispondono ai contenuti (ad esempio un tono serio per le ultime notizie o un tono caldo e paziente per le istruzioni di cucina passo passo).

Questa guida mostra come generare la sintesi vocale dall'input di testo con uno o più speaker e come riprodurre in streaming la risposta audio.

Vai al codice per un singolo oratore Vai al codice per più oratori Vai al codice per le risposte in streaming

Confronto tra la sintesi vocale e Live API

Sia i modelli di sintesi vocale (TTS) sia i modelli Live API sono modelli a bassa latenza che generano voce e possono essere configurati per diverse voci di risposta e lingue. Tuttavia, servono casi d'uso molto diversi.

  • La generazione di sintesi vocale (TTS) è un'interazione unidirezionale di richiesta-risposta (testo in entrata, audio in uscita). È pensato per scenari che richiedono la recitazione esatta del testo fornito con un controllo granulare su stile e suono, come la narrazione di podcast, audiolibri o la lettura di articoli ad alta voce.

  • La generazione di Live API supporta lo streaming bidirezionale per le conversazioni vocali in tempo reale (voce in entrata, voce in uscita). È eccellente in contesti conversazionali dinamici in cui il modello decide il discorso applicabile da restituire. Tieni presente che i modelli Live API più recenti supportano anche l'input di video e immagini.

Prima di iniziare

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Se non l'hai ancora fatto, completa la guida introduttiva, che descrive come configurare il progetto Firebase, connettere l'app a Firebase, aggiungere l'SDK, inizializzare il servizio di backend per il provider Gemini API scelto e creare un'istanza GenerativeModel.

Per testare e perfezionare i prompt, ti consigliamo di utilizzare Google AI Studio.

Modelli che supportano questa funzionalità

  • gemini-3.1-flash-tts-preview

Generare parlato dal testo

Puoi generare la voce dal testo fornito utilizzando un modello TTS Gemini.

Generare un discorso con un unico oratore

Prima di provare questo esempio, completa la sezione Prima di iniziare di questa guida per configurare il progetto e l'app.
In questa sezione, fai clic anche su un pulsante per il provider Gemini API che hai scelto, in modo da visualizzare i contenuti specifici del provider in questa pagina.

Puoi configurare il modello in modo che generi l'audio utilizzando una sola voce.

Nel tuo GenerationConfig, includi quanto segue:

Chiama generateContent con il tuo prompt testuale. Il modello restituisce dati audio PCM non elaborati nelle parti della risposta.

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

Per Kotlin, i metodi in questo SDK sono funzioni di sospensione e devono essere chiamati da un ambito di coroutine.

// 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

Per Java, i metodi di streaming in questo SDK restituiscono un tipo Publisher dalla libreria 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);
    }
  }
}

Generare voci con più relatori

Prima di provare questo esempio, completa la sezione Prima di iniziare di questa guida per configurare il progetto e l'app.
In questa sezione, fai clic anche su un pulsante per il provider Gemini API che hai scelto, in modo da visualizzare i contenuti specifici del provider in questa pagina.

Puoi configurare il modello in modo che utilizzi voci diverse per i diversi interlocutori nel testo. Ciò è utile per generare audio per dialoghi o conversazioni.

  1. Crea un MultiSpeakerVoiceConfig che mappi i nomi degli oratori (che utilizzerai nel prompt) a nomi di voci di risposta specifici (ad esempio, Kore).

    La configurazione multi-speaker supporta esattamente due speaker.

  2. Nel tuo GenerationConfig, includi quanto segue:

    • Imposta responseModalities in modo che includa AUDIO.

    • Configura un SpeechConfig con quanto segue:

  3. Nel prompt, indica chi sta parlando utilizzando i nomi degli oratori come prefissi (ad esempio, Joe: Hello. Jane: Hi.).

Chiama generateContent con il tuo prompt testuale. Il modello restituisce dati audio PCM non elaborati nelle parti della risposta.

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

Per Kotlin, i metodi in questo SDK sono funzioni di sospensione e devono essere chiamati da un ambito di coroutine.

// 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

Per Java, i metodi di streaming in questo SDK restituiscono un tipo Publisher dalla libreria 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);
    }
  }
}

Visualizzare in streaming la risposta

Prima di provare questo esempio, completa la sezione Prima di iniziare di questa guida per configurare il progetto e l'app.
In questa sezione, fai clic anche su un pulsante per il provider Gemini API che hai scelto, in modo da visualizzare i contenuti specifici del provider in questa pagina.

Puoi ottenere interazioni più rapide e una latenza inferiore riproducendo in streaming la risposta audio man mano che viene generata, anziché attendere il completamento dell'intero file audio.

Lo streaming della voce generata è supportato sia per le configurazioni con un solo oratore sia per quelle con più oratori. È supportato solo quando vengono utilizzati i modelli Gemini 3.x TTS.

Per trasmettere in streaming la risposta vocale, chiama generateContentStream anziché generateContent e gestisci i chunk man mano che arrivano. I seguenti esempi mostrano come trasmettere in streaming una risposta di un singolo oratore:

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

Per Kotlin, i metodi in questo SDK sono funzioni di sospensione e devono essere chiamati da un ambito di coroutine.

// 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

Per Java, i metodi di streaming in questo SDK restituiscono un tipo Publisher dalla libreria 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);
    }
}



Controllare la sintesi vocale con i prompt

Puoi influenzare il tono, il ritmo e lo stile della sintesi vocale generata utilizzando tecniche di prompt specifiche.

Le seguenti sottosezioni sulla struttura dei prompt e sui tag audio descrivono linee guida di alto livello. Per indicazioni dettagliate, consulta questa guida ai prompt.

Struttura del prompt

Per ottenere risultati ottimali, struttura il prompt con i seguenti componenti:

  • Audio Profile: descrivi la personalità, l'identità principale e l'archetipo dell'oratore (ad esempio, A warm, professional narrator).

  • Scene: descrivi l'ambiente e l'atmosfera emotiva (ad esempio, In a quiet library o Amidst a noisy crowd).

  • Director's Notes: descrivi l'emozione, il ritmo, lo stile e l'accento (ad esempio, Speak slowly and with mystery).

  • Sample Context: fornisci al modello un punto di partenza (ad esempio, The speaker is greeting a close friend).

  • Trascrizione: il testo effettivo da pronunciare. Per ottenere prestazioni ottimali, assicurati che il tono e il contesto del testo siano in linea con il profilo vocale e le note di regia.

Prompt di esempio:

[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!

Etichette per l'audio

Puoi inserire tag di formattazione direttamente nel prompt testuale per guidare le prestazioni del modello.

I tag audio sono supportati solo quando vengono utilizzati i modelli Gemini 3.x TTS.

I tag di uso comune includono:

  • [whispers]: Sussurrare
  • [laughs]: Per aggiungere una risata
  • [giggles]: Per aggiungere risate
  • [sighs]: Per aggiungere un sospiro
  • [gasp]: Per aggiungere un sospiro
  • [shouting]: Per urlare
  • [excited]: Per parlare con entusiasmo
  • [serious]: Per parlare seriamente
  • [sighs whispers]: Emozioni combinate (puoi combinare i tag)

Tieni presente quanto segue quando utilizzi i tag audio:

  • Nessun elenco esaustivo: non esiste un elenco fisso di tag supportati. Puoi sperimentare con diverse emozioni ed espressioni (ad esempio [bored], [sarcastically] o anche [like dracula]) per vedere come cambia l'output.

  • Prompt testuale non in inglese: se il prompt testuale non è in inglese, devi comunque utilizzare i tag audio in inglese per ottenere risultati ottimali.

Prompt di esempio:

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



Limitazioni e requisiti

Tieni presente le seguenti limitazioni e requisiti quando utilizzi la generazione di voci:

  • La configurazione multi-speaker supporta esattamente due speaker.

  • Le seguenti funzionalità sono supportate solo quando utilizzi i modelli Gemini 3.x TTS: streaming, tag audio e lingue aggiuntive rilevate automaticamente.

Vincoli per gemini-3.1-flash-tts-preview

  • Incoerenza della voce: l'output del modello potrebbe non corrispondere sempre rigorosamente all'oratore selezionato se il tono e il contesto del prompt non sono in linea con il profilo dell'oratore (ad esempio, una voce maschile profonda che tenta di parlare come una bambina). Assicurati che il contesto del prompt corrisponda alla voce.
  • Output più lunghi: la qualità e la coerenza della voce potrebbero peggiorare per l'audio più lungo di qualche minuto. Ti consigliamo di dividere i prompt di testo lunghi in parti più piccole.
  • Restituzione occasionale di token di testo: il modello a volte restituisce token di testo anziché token audio, causando l'esito negativo della richiesta con un errore 500. Poiché questo si verifica in modo casuale in una piccola percentuale di richieste, devi implementare la logica di ripetizione dei tentativi nella tua app.
  • Rifiuti errati del classificatore: i prompt vaghi potrebbero non superare il classificatore di sintesi vocale, con conseguente rifiuto della richiesta (PROHIBITED_CONTENT) o indurre il modello a leggere ad alta voce le istruzioni di stile. Per evitare questo problema, utilizza un prompt strutturato con un'introduzione chiara (ad esempio Audio Profile e Director's Notes) all'inizio del prompt.



Voci e lingue supportate

I modelli TTS Gemini prendono l'input di testo e generano l'uscita audio, quindi la risposta è la sintesi vocale stessa. Le seguenti sottosezioni elencano le voci e le lingue supportate che i modelli TTS Gemini possono "parlare" (o in cui possono rispondere).

Le voci sono multilingue, il che significa che puoi utilizzare la stessa voce per generare la sintesi vocale in una qualsiasi delle lingue supportate. Ad esempio, puoi impostare la voce su Kore e inviare una serie di prompt di testo in spagnolo, hindi e vietnamita. Le risposte saranno tutte nella voce di Kore, ma in ciascuna delle diverse lingue.

Nomi delle voci

I modelli TTS Gemini supportano 30 diverse voci HD sintetizzate, ciascuna con caratteristiche distinte. Puoi visualizzare un elenco di opzioni vocali per le risposte e ascoltare le demo di ogni voce espandendo la sezione seguente.

Lingue

I modelli TTS Gemini possono rilevare automaticamente le seguenti lingue nel prompt testuale. Il parlato generato sarà in quella lingua.

Tieni presente che, se vuoi, puoi impostare esplicitamente un codice lingua nella configurazione del parlato.

Lingue supportate da tutti i modelli di generazione audio
Lingua Codice BCP-47 Lingua Codice BCP-47
Arabo (egiziano) ar-EG Tedesco (Germania) de-DE
Inglese (USA) en-US Spagnolo (USA) es-US
Francese (Francia) fr-FR Hindi (India) hi-IN
Indonesiano (Indonesia) id-ID Italiano (Italia) it-IT
Giapponese (Giappone) ja-JP Coreano (Corea) ko-KR
Portoghese (Brasile) pt-BR Russo (Russia) ru-RU
Olandese (Paesi Bassi) nl-NL Polacco (Polonia) pl-PL
Thailandese (Thailandia) th-TH Turco (Turchia) tr-TR
Vietnamita (Vietnam) vi-VN Rumeno (Romania) ro-RO
Ucraino (Ucraina) uk_UA Bengalese (Bangladesh) bn-BD
Inglese (India) Bundle en-IN e hi-IN Marathi (India) mr-IN
Tamil (India) ta-IN Telugu (India) te-IN
Altre lingue supportate dai modelli 3.x che generano audio
Lingua Codice BCP-47 Lingua Codice BCP-47
Afrikaans af Filippino fil
Albanese sq Finlandese fi
Amarico am Galiziano gl
Armeno hy Georgiano ka
Azero az Greek el
Basco eu Gujarati gu
Bielorusso be Creolo haitiano ht
Bulgaro bg Ebraico he
Birmano mio Ungherese hu
Catalano ca Islandese è
Cebuano ceb Giavanese jv
Cinese, mandarino cmn Kannada kn
Croato h Konkani kok
Ceco cs Lao lo
Danese da Latino la
Estone et Lettone lv
Lituano lt Lussemburghese lb
Macedone mk Maithili mai
Malgascio mg Malese ms
Malayalam ml Mongolo mn
Nepali ne Norvegese, bokmål nb
Norvegese, nynorsk nn Odia o
Pashto ps Persiano fa
Punjabi pa Serbo sr
Sindhi sd Singalese si
Slovak sk Sloveno sl
Swahili sw Swedish sv
Urdu ur

(Facoltativo) Imposta esplicitamente un codice lingua

Se non specifichi un codice di lingua nella configurazione vocale, il modello rileva automaticamente la lingua nel prompt testuale.

Tuttavia, puoi impostare esplicitamente la lingua (utilizzando il parametro languageCode nella configurazione vocale). A tale scopo, devi utilizzare uno dei seguenti codici delle impostazioni internazionali BCP-47 supportati:

  • Arabo: ar-XA
  • Bengalese: bn-IN
  • Cinese (mandarino): cmn-CN
  • Olandese: nl-NL
  • Inglese: en-US, en-GB, en-AU, en-IN
  • Francese: fr-FR, fr-CA
  • Tedesco: de-DE
  • Gujarati: gu-IN
  • Hindi: hi-IN
  • Indonesiano: id-ID
  • Italiano: it-IT
  • Giapponese: ja-JP
  • Kannada: kn-IN
  • Coreano: ko-KR
  • Malayalam: ml-IN
  • Marathi: mr-IN
  • Polacco: pl-PL
  • Portoghese: pt-BR
  • Russo: ru-RU
  • Spagnolo: es-US, es-ES
  • Tamil: ta-IN
  • Telugu: te-IN
  • Thai: th-TH
  • Turco: tr-TR
  • Vietnamita: vi-VN



Cos'altro puoi fare?

Prova altre funzionalità

Scopri come controllare la generazione di contenuti

Puoi anche sperimentare con prompt e configurazioni del modello e persino ottenere uno snippet di codice generato utilizzando Google AI Studio.

Scopri di più sui modelli supportati

Scopri di più sui modelli disponibili per vari casi d'uso e sulle relative quote e prezzi.


Fornisci un feedback sulla tua esperienza con Firebase AI Logic