Синтез речи (TTS) с помощью Gemini API


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

Генерация речи из текста контролируема, то есть вы предоставляете точный текст, который нужно озвучить. Вы также можете использовать естественный язык в своих подсказках, чтобы задать стиль, акцент, темп и тон аудиовыхода. Синтез речи – это процесс, обратный расшифровке (преобразованию речи в текст).

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

Вот что можно делать с помощью этой функции:

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

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

  • Контекстно-зависимые средства чтения контента. Читайте новостные статьи, рецепты или записи в блогах вслух, используя голос и эмоциональный тон, соответствующие контенту (например, серьезный тон для срочных новостей или теплый, терпеливый тон для пошаговых инструкций по приготовлению пищи).

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

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

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

Модели преобразования текста в речь (TTS) и модели Live API – это модели генерации речи с низкой задержкой, которые можно настроить для разных голосов и языков. Однако они служат для разных целей.

  • Синтез речи – это однонаправленное взаимодействие по принципу "запрос – ответ" (текст на входе, аудио на выходе). Она подходит для ситуаций, когда требуется точное воспроизведение предоставленного текста с детальным контролем над стилем и звуком, например для озвучивания подкастов, аудиокниг или чтения статей вслух.

  • Live API generation поддерживает двунаправленную потоковую передачу для голосовых разговоров в реальном времени (голосовой ввод и вывод). Она отлично подходит для динамических разговоров, в которых модель сама решает, что ответить. Обратите внимание, что последние модели Live API также поддерживают видео и изображения.

Подготовка

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

Если вы ещё этого не сделали, ознакомьтесь с кратким руководством, в котором рассказывается, как настроить проект Firebase, подключить приложение к Firebase, добавить SDK, инициализировать бэкенд-службу для выбранного поставщика Gemini API и создать экземпляр GenerativeModel.

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

Модели, поддерживающие эту функцию

  • gemini-3.1-flash-tts-preview

Генерируйте речь из текста

Вы можете генерировать речь из текста с помощью модели TTS Gemini.

Генерировать речь с одним говорящим

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

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

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

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

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

В 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: [ResponseModalities.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);

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

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

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

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

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

Unity


using Firebase.AI;

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

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

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

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

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

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

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

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

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

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

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

    Конфигурация с несколькими колонками поддерживает ровно две колонки.

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

    • Задайте для параметра responseModalities значение AUDIO.

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

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

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

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

В 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: [ResponseModalities.audio],
  speechConfig: multiSpeechConfig,
);

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

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

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

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

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

Unity


using Firebase.AI;

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

var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);

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

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

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

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

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

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

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

Включить потоковую передачу ответов

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

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

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

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

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

В 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: [ResponseModalities.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore'),
);

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

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

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

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

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

Unity


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

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

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

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

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

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

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

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

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



Как управлять речевым выводом с помощью запросов

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

В подразделах ниже приведены общие рекомендации по структуре запросов и аудиотегам. Подробные инструкции вы найдете в руководстве по составлению запросов.

Структура запроса

Чтобы получить наилучшие результаты, включите в запрос следующие компоненты:

  • 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]: комбинированные эмоции (можно сочетать теги)

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

  • Нет полного списка. Фиксированного списка поддерживаемых тегов не существует. Вы можете поэкспериментировать с разными эмоциями и выражениями (например, [bored], [sarcastically] или даже [like dracula]), чтобы посмотреть, как изменится результат.

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

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

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



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

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

  • Конфигурация с несколькими колонками поддерживает ровно две колонки.

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

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

  • Несоответствие голоса. Результат, сгенерированный моделью, может не всегда точно соответствовать выбранному голосу, если тон и контекст запроса не соответствуют профилю говорящего (например, глубокий мужской голос пытается говорить как молодая девушка). Убедитесь, что контекст запроса соответствует голосу.
  • Длинные аудио. Качество и согласованность речи могут ухудшаться в аудиозаписях длиннее нескольких минут. Рекомендуем разбивать длинные текстовые запросы на более короткие.
  • Иногда возвращаются текстовые токены. Модель иногда возвращает текстовые токены вместо аудиотокенов, из-за чего запрос завершается ошибкой 500. Поскольку это происходит случайным образом в небольшом проценте запросов, вам следует реализовать в своем приложении логику повторных попыток.
  • Ложные отклонения классификатора. Неточные запросы могут не пройти классификатор синтеза речи, что приведет к отклонению запроса (PROHIBITED_CONTENT) или к тому, что модель прочитает инструкции по стилю вслух. Чтобы избежать этого, используйте структурированный запрос с четкими вводными инструкциями (например, Audio Profile и Director's Notes) в начале запроса.



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

Модели TTS Gemini принимают текстовые входные данные и генерируют аудиовыход, поэтому ответом является сама синтезированная речь. В следующих подразделах перечислены поддерживаемые голоса и языки, на которых могут "говорить" (или отвечать) модели TTS Gemini.

Голоса многоязычные, то есть вы можете использовать один и тот же голос для генерации речи на любом из поддерживаемых языков. Например, вы можете выбрать голос Kore и отправить набор текстовых запросов на испанском, вьетнамском и хинди. Ответы будут озвучены голосом Kore на разных языках.

Названия голосов

Модели TTS Gemini поддерживают 30 синтезированных HD-голосов с разными характеристиками. Чтобы посмотреть список вариантов голоса и послушать их демоверсии, разверните раздел ниже.

Языки

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

Обратите внимание, что вы можете явно задать код языка в конфигурации речи.

Языки, поддерживаемые всеми моделями генерации аудио
Язык Код BCP-47 Язык Код BCP-47
Арабский (Египет) ar-EG немецкий (Германия) de-DE
Английский (США) en-US Испанский (США) es-US
Французский (Франция) fr-FR Хинди (Индия) hi-IN
Индонезийский (Индонезия) id-ID (индонезийский, Индонезия) итальянский (Италия) it-IT
Японский (Япония) ja-JP Корейский (Корея) ko-KR
Португальский (Бразилия) pt-BR русский (Россия) ru-RU
Нидерландский (Нидерланды) nl-NL Польский (Польша) pl-PL
Тайский (Таиланд) th-TH Турецкий (Турция) tr-TR
Вьетнамский (Вьетнам) vi-VN Румынский (Румыния) ro-RO
Украинский (Украина) uk-UA бенгальский (Бангладеш) bn-BD
Английский (Индия) Пакет en-IN и hi-IN Маратхи (Индия) mr-IN
Тамильский (Индия) ta-IN Телугу (Индия) te-IN
Дополнительные языки, поддерживаемые моделями 3.x для генерации аудио
Язык Код BCP-47 Язык Код BCP-47
Африкаанс af Филиппинский fil
Албанский sq Финский fi
Амхарский am Галицийский gl
Армянский hy Грузинский ka
Азербайджанский az Греческий el
Баскский eu Гуджарати gu
Белорусский be Гаитянский креольский ht
Болгарский bg Иврит он
Бирманский my Венгерский hu
Каталанский ca Исландский –
Себуанский ceb Яванский jv
Китайский (севернокитайский) cmn Каннада kn
Хорватский ч. Конкани kok
Чешский cs Лаосский lo
Датский da Латинский la
Эстонский et Латышский lv
Литовский lt Люксембургский фнт
Македонский mk Майтхили mai
Малагасийский мг Малайский ms
Малаялам ml Монгольский mn
Непальский ne Норвежский (букмол) nb
Норвежский (нюнорск) nn Ория или
Пушту ps Персидское происхождение fa
Пенджабский pa Сербский sr
Синдхи sd Сингальский si
Словацкий sk Словенский sl
Суахили sw Шведский sv
Урду ur

(Необязательно) Явно задайте код языка.

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

Однако вы можете явно задать язык, используя параметр languageCode в конфигурации речи. Для этого необходимо использовать один из следующих поддерживаемых кодов региональных настроек BCP-47:

  • Арабский: 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