Генерация речи (TTS) с использованием API Gemini


Вы можете попросить модель Gemini TTS сгенерировать речевой (аудио) вывод на основе текстовой подсказки. При использовании Firebase AI Logic вы можете сделать этот запрос непосредственно из своего приложения.

Text-to-speech (TTS) generation is controllable , meaning that you provide the exact text to synthesize into speech. Also, you can use natural language in your prompts to guide the style, accent, pace, and tone of the audio output. You can think of TTS as the opposite of transcription (speech-to-text) .

Эта функция доступна при использовании любой из моделей Gemini -tts , оптимизированных для генерации высококачественной речи с низкой задержкой.

Благодаря этой возможности вы можете делать, например, следующее:

  • Interactive storytelling : Create immersive audiobooks or role-playing games where the model switches voices for different characters or adapts its tone (like whispering in suspense or laughing at a joke) to match the narrative.

  • Изучение языка : Разработайте руководства по произношению, которые позволят читать текст с учетом региональных акцентов или в более медленном темпе, чтобы помочь учащимся практиковать сложные произношения.

  • Context-aware content readers : Read news articles, recipes, or blog posts aloud using a voice persona and emotional tone that matches the content (such as a serious tone for breaking news or a warm, patient tone for step-by-step cooking instructions).

В этом руководстве показано, как генерировать речь из текстового ввода с участием одного или нескольких говорящих, а также как передавать аудиоответ в потоковом режиме.

Перейти к коду для одного говорящего Перейти к коду для нескольких говорящих Перейти к коду для потоковых ответов

Сравнение TTS и Live API

Both text-to-speech (TTS) models and Live API models are low-latency, speech-generating models that can be configured for different response voices and languages. However, they serve very different use cases.

  • Text-to-speech (TTS) generation is a unidirectional , request-response interaction (text in, audio out). It's tailored for scenarios that require exact recitation of the provided text with fine-grained control over style and sound, such as podcast narration, audiobooks, or reading articles aloud.

  • Live API generation supports bidirectional streaming for real-time voice conversations (voice in, voice out). It excels in dynamic conversational contexts where the model decides the applicable speech to return. Note that the latest Live API models also support video and image input.

Прежде чем начать

Чтобы просмотреть контент и код, относящиеся к вашему поставщику API Gemini , нажмите на него.

Agent

If you haven't already, complete the getting started guide , which describes how to set up your Firebase project, connect your app to Firebase, add the SDK, initialize the backend service for your chosen Gemini API provider, and create a GenerativeModel instance.

Для тестирования и доработки ваших подсказок мы рекомендуем использовать Google AI Studio .

Модели, поддерживающие эту возможность

  • gemini-3.1-flash-tts-preview

Создание речи из текста

Вы можете генерировать речь из предоставленного текста, используя модель синтеза речи Gemini .

Создание речи с помощью одного говорящего

Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение.
В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику .

Вы можете настроить модель для вывода звука с использованием одного голоса.

В файл GenerationConfig добавьте следующее:

Вызовите generateContent с текстовым запросом. Модель возвращает необработанные аудиоданные в формате PCM в части ответа.

Быстрый


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

В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .

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

В Java потоковые методы в этом SDK возвращают тип Publisher из библиотеки 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);
}

Единство


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);
    }
  }
}

Генерация речи с участием нескольких говорящих

Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение.
В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику .

Вы можете настроить модель так, чтобы она использовала разные голоса для разных говорящих в тексте. Это полезно для генерации аудио для диалогов или разговоров.

  1. Создайте объект MultiSpeakerVoiceConfig , который сопоставляет имена говорящих (которые вы будете использовать в своем запросе) с именами конкретных голосов для ответов (например, Kore ).

    Многоканальная конфигурация поддерживает подключение ровно 2 динамиков.

  2. В файл GenerationConfig добавьте следующее:

    • Установите для параметра responseModalities значение AUDIO .

    • Настройте SpeechConfig следующим образом:

  3. В задании укажите, кто говорит, используя имена говорящих в качестве префиксов (например, Joe: Hello. Jane: Hi. ).

Вызовите generateContent с текстовым запросом. Модель возвращает необработанные аудиоданные в формате PCM в части ответа.

Быстрый


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

В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .

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

В Java потоковые методы в этом SDK возвращают тип Publisher из библиотеки 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);
}

Единство


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);
    }
  }
}

Трансляция ответа

Прежде чем опробовать этот пример, выполните раздел «Перед началом работы » этого руководства, чтобы настроить свой проект и приложение.
В этом разделе вам также нужно будет нажать кнопку для выбранного вами поставщика API Gemini , чтобы увидеть на этой странице контент, относящийся к данному поставщику .

Для ускорения взаимодействия и снижения задержки можно передавать аудиоответ по мере его генерации, вместо того чтобы ждать завершения обработки всего аудиофайла.

Поддерживается потоковая передача сгенерированной речи как для одноголосных , так и для многоголосных конфигураций. Поддержка осуществляется только при использовании моделей Gemini 3.x TTS .

Для потоковой передачи речевого ответа вызовите generateContentStream вместо generateContent и обрабатывайте фрагменты по мере их поступления. Следующие примеры показывают, как передавать потоком ответ одного говорящего:

Быстрый


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

В Kotlin методы в этом SDK являются функциями приостановки и должны вызываться из области видимости сопрограммы .

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

В Java потоковые методы в этом SDK возвращают тип Publisher из библиотеки 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);
  }
}

Единство


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);
    }
}



Управляйте речевым выводом с помощью подсказок.

Вы можете влиять на тон, темп и стиль генерируемой речи, используя специальные методы подсказок.

В следующих подразделах, посвященных структуре подсказок и аудиометкам, изложены общие рекомендации. Для получения более подробных указаний обратитесь к данному руководству по использованию подсказок .

Подсказка по структуре

Для достижения наилучших результатов структурируйте ваше задание, используя следующие компоненты:

  • Audio Profile : Опишите личность, основную идентичность и архетип говорящего (например, A warm, professional narrator »).

  • Scene : Опишите окружающую среду и эмоциональную атмосферу (например, In a quiet library или Amidst a noisy crowd »).

  • Director's Notes : Опишите эмоции, темп, стиль и акцент (например, Speak slowly and with mystery ).

  • Sample Context : Задайте модели отправную точку (например, The speaker is greeting a close friend ).

  • Транскрипт : Сам текст, который необходимо произнести. Для достижения наилучшего результата убедитесь, что тон и контекст текста соответствуют голосовому профилю и указаниям режиссера.

Пример подсказки:

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

Аудиотеги

Вы можете вставлять теги форматирования непосредственно в текстовое поле запроса, чтобы управлять работой модели.

Поддержка аудиотегов доступна только при использовании моделей Gemini 3.x TTS .

К числу часто используемых тегов относятся:

  • [whispers] : Говорить шепотом
  • [laughs] : Чтобы добавить смеха
  • [giggles] : Чтобы добавить смеха
  • [sighs] : Добавить вздох
  • [gasp] : Добавить вздох
  • [shouting] : Кричать
  • [excited] : говорить с возбуждением
  • [serious] : Говорить серьезно
  • [sighs whispers] : Совокупность эмоций (можно комбинировать теги)

При использовании аудиотегов обратите внимание на следующее:

  • No exhaustive list : There's no fixed list of supported tags. You can experiment with different emotions and expressions (like [bored] , [sarcastically] , or even [like dracula] ) to see how the output changes.

  • Текстовая подсказка не на английском языке : Если ваша текстовая подсказка не на английском языке, для достижения наилучших результатов все равно следует использовать аудиотеги на английском языке.

Пример подсказки:

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



Ограничения и требования

При использовании генератора речи следует учитывать следующие ограничения и требования:

  • Многоканальная конфигурация поддерживает подключение ровно 2 динамиков.

  • Следующие функции поддерживаются только при использовании моделей Gemini 3.x TTS : потоковая передача, аудиотеги и дополнительные языки, определяемые автоматически.

Ограничения для gemini-3.1-flash-tts-preview

  • Voice inconsistency : The model's output might not always strictly match the selected speaker if your prompt's tone and context don't align with the speaker's profile (for example, a deep male voice attempting to speak like a young girl). Ensure your prompt context matches the voice.
  • Более длинные аудиозаписи : качество и согласованность речи могут меняться при воспроизведении аудиозаписей продолжительностью более нескольких минут. Мы рекомендуем разбивать длинные текстовые подсказки на более мелкие фрагменты.
  • Occasional text token returns : The model occasionally returns text tokens instead of audio tokens, causing the request to fail with a 500 error. Because this occurs randomly in a small percentage of requests, you should implement retry logic in your app.
  • Classifier false rejections : Vague prompts might fail the speech synthesis classifier, resulting in a rejected request ( PROHIBITED_CONTENT ) or causing the model to read your style instructions aloud. To avoid this, use a structured prompt with a clear preamble (like Audio Profile and Director's Notes ) at the beginning of the prompt.



Поддерживаемые голоса и языки

The Gemini TTS models take text input and generate audio output, so the response is the synthesized speech itself. The following subsections list the supported voices and languages that the Gemini TTS models can "speak" (or respond in).

The voices are multilingual, which means you can use the same voice to generate speech in any of the supported languages. For example, you can set the voice to Kore and send a set of text prompts in Spanish, Hindi, and Vietnamese. The responses will all be in the Kore voice, but in each of those different languages.

Голосовые имена

The Gemini TTS models support 30 different synthisized HD voices, each with distinct characteristics. You can view a list of response voice options and hear demos of each voice by expanding the section below.

Языки

Модели Gemini TTS могут автоматически определять следующие языки в вашем текстовом запросе. Сгенерированная речь будет на этом языке.

Обратите внимание, что при желании вы можете явно указать код языка в настройках речи.

Языки, поддерживаемые всеми моделями устройств для генерации аудио.
Язык Код BCP-47 Язык Код BCP-47
Арабский (египетский) ар-ЭГ Немецкий (Германия) де-ДЕ
Английский (США) en-US Испанский (США) es-US
Французский (Франция) фр-ФР Хинди (Индия) хай-ИН
Индонезийский (Индонезия) я сделал Итальянский (Италия) ИТ-ИТ
Японский (Япония) ja-JP Корейский (Корея) ко-КР
Португальский (Бразилия) пт-БР Русский (Россия) ру-RU
Голландский (Нидерланды) nl-NL Польский (Польша) пл-ПЛ
Тайский (Таиланд) th-TH Турецкий (Турция) тр-ТР
Вьетнамский (Вьетнам) vi-VN Румынский (Румыния) ро-ро
Украинский (Украина) Великобритания-Украина Бенгальский (Бангладеш) бн-БД
Английский (Индия) en-IN & hi-IN bundle Маратхи (Индия) мистер-ИН
Тамильский (Индия) та-ИН Телугу (Индия) те-ИН
Дополнительные языки, поддерживаемые моделями с аудиогенерацией версии 3.x.
Язык Код BCP-47 Язык Код BCP-47
африкаанс аф филиппинский фил
албанский кв. финский фи
амхарский являюсь галисийский гл
армянский хай грузинский ка
азербайджанский аз греческий эль
Баскский Евросоюз гуджарати гу
белорусский быть гаитянский креольский хт
болгарский бг иврит он
бирманский мой венгерский ху
каталанский ка исландский является
Себуано цеб яванский джв
Китайский, мандаринский диалект китайского языка смн Каннада кн
хорватский ч Конкани кок
чешский кс Лао ло
датский да латинский ла
эстонский и латышский lv
литовский лт люксембургский фунт
македонский мк Майтхили май
малагасийский мг малайский РС
Малаялам мл монгольский мн
непальский не норвежский, букмол нб
Норвежский, Нюнорск нн Одиа или
пушту пс персидский фа
Пенджаби па сербский ст.
Синдхи sd сингальский си
словацкий ск словенский сл
суахили sw шведский св
урду ур

(Необязательно) Явно укажите код языка

Если вы не укажете код языка в настройках речи, модель автоматически определит язык в текстовом запросе.

However, you can optionally explicitly set the language (using the languageCode parameter in the speech configuration). To do this, you must use one of the following supported BCP-47 locale codes:

  • Арабский : ar-XA
  • Бенгальский : bn-IN
  • Китайский (мандаринский) : cmn-CN
  • Голландский : nl-NL
  • Английский : en-US , en-GB , en-AU , en-IN
  • Французский : fr-FR , fr-CA
  • Немецкий : de-DE
  • Гуджарати : gu-IN
  • Хинди : hi-IN
  • Индонезийский : id-ID
  • Итальянский : it-IT
  • Японский : ja-JP
  • Каннада : kn-IN
  • Корейский : ko-KR
  • Малаялам : ml-IN
  • Маратхи : mr-IN
  • Польский : pl-PL
  • Португальский : pt-BR
  • Русский : ru-RU
  • Испанский : es-US , es-ES
  • Тамильский : ta-IN
  • Телугу : te-IN
  • Тайский : th-TH
  • Турецкий : tr-TR
  • Вьетнамский : vi-VN



Что еще можно сделать?

Попробуйте другие возможности.

Узнайте, как управлять генерацией контента.

Вы также можете поэкспериментировать с подсказками и настройками модели, а также получить сгенерированный фрагмент кода с помощью Google AI Studio .

Узнайте больше о поддерживаемых моделях

Узнайте о моделях, доступных для различных вариантов использования , а также об их квотах и ​​ценах .


Оставьте отзыв о вашем опыте использования Firebase AI Logic.