Gemini API を使用したテキスト読み上げ(TTS)の生成


Gemini TTS モデルに、テキスト プロンプトから音声(オーディオ)出力を生成するようにリクエストできます。Firebase AI Logic を使用すると、このリクエストをアプリから直接行うことができます。

テキスト読み上げ(TTS)生成は制御可能です。つまり、音声に合成する正確なテキストを指定します。また、プロンプトで自然言語を使用して、音声出力のスタイル、アクセント、速度、トーンを指示することもできます。TTS は、音声文字変換(音声入力)の逆と考えることができます。

この機能は、高品質で低レイテンシの音声生成に最適化された Gemini -tts モデルのいずれかで使用できます。

この機能を使用すると、次のようなことができます。

  • インタラクティブなストーリーテリング: 没入型のオーディオブックやロールプレイング ゲームを作成します。モデルは、キャラクターごとに声を切り替えたり、ストーリーに合わせてトーンを調整したり(サスペンスでささやいたり、ジョークで笑ったり)します。

  • 言語学習: 特定の地域のアクセントや、学習者が難しい発音を練習できるようにゆっくりとしたペースでテキストを読み上げることができる発音ガイドを作成します。

  • コンテキストを認識するコンテンツ リーダー: ニュース記事、レシピ、ブログ投稿を、コンテンツに合った音声ペルソナと感情的なトーン(ニュース速報の場合は真剣なトーン、料理の手順の場合は温かく忍耐強いトーンなど)で読み上げます。

このガイドでは、単一または複数の話者によるテキスト入力から音声を生成する方法と、音声レスポンスをストリーミングする方法について説明します。

単一話者のコードに移動 複数話者のコードに移動 ストリーミング レスポンスのコードに移動

TTS と Live API の比較

テキスト読み上げ(TTS)モデルと Live API モデルはどちらも、さまざまなレスポンス音声と言語に構成できる低レイテンシの音声生成モデルです。ただし、ユースケースは大きく異なります。

  • テキスト読み上げ(TTS)生成は、一方向のリクエスト / レスポンス型のインタラクション(テキスト入力、音声出力)です。ポッドキャストのナレーション、オーディオブック、記事の読み上げなど、スタイルや音声をきめ細かく制御して、提供されたテキストを正確に読み上げる必要があるシナリオに合わせて調整されています。

  • Live API 世代は、リアルタイムの音声会話(音声入力、音声出力)の双方向ストリーミングをサポートしています。モデルが返す適切な音声を決定する動的な会話コンテキストに優れています。最新の Live API モデルは、動画と画像の入力もサポートしています。

始める前に

Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。

まだ完了していない場合は、スタートガイドに沿って、Firebase プロジェクトの設定、アプリと Firebase の連携、SDK の追加、選択した Gemini API プロバイダのバックエンド サービスの初期化、GenerativeModel インスタンスの作成を行います。

プロンプトのテストと反復処理には、Google AI Studio を使用することをおすすめします。

この機能をサポートするモデル

  • gemini-3.1-flash-tts-preview

テキストから音声を生成する

Gemini TTS モデルを使用して、指定されたテキストから音声を生成できます。

1 人の話者による音声を生成する

このサンプルを試す前に、このガイドの始める前にセクションを完了して、プロジェクトとアプリを設定してください。
このセクションでは、選択した Gemini API プロバイダのボタンをクリックして、このページにプロバイダ固有のコンテンツを表示します。

1 つの音声を使用して音声を出力するようにモデルを構成できます。

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 のメソッドは suspend 関数であり、コルーチン スコープから呼び出す必要があります。

// 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 のストリーミング メソッドは、Reactive Streams ライブラリから Publisher 型を返します。

// 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. 話者名(プロンプトで使用する名前)を特定のレスポンス音声名(Kore など)にマッピングする MultiSpeakerVoiceConfig を作成します。

    マルチスピーカー構成では、2 つのスピーカーがサポートされます。

  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 のメソッドは suspend 関数であり、コルーチン スコープから呼び出す必要があります。

// 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 のストリーミング メソッドは、Reactive Streams ライブラリから Publisher 型を返します。

// 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 モデルを使用する場合にのみサポートされます。

音声レスポンスをストリーミングするには、generateContent ではなく generateContentStream を呼び出し、チャンクが到着したときに処理します。次の例は、単一話者のレスポンスをストリーミングする方法を示しています。

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 のメソッドは suspend 関数であり、コルーチン スコープから呼び出す必要があります。

// 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 のストリーミング メソッドは、Reactive Streams ライブラリから Publisher 型を返します。

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

  • Transcript: 実際に読み上げられるテキスト。最適なパフォーマンスを得るには、テキストのトーンとコンテキストが音声プロファイルとディレクション ノートに沿っていることを確認してください。

サンプル プロンプト:

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



制限事項と要件

音声生成を使用する場合は、次の制限と要件に注意してください。

  • マルチスピーカー構成では、2 つのスピーカーがサポートされます。

  • 次の機能は、Gemini 3.x TTS モデルを使用する場合にのみサポートされます。ストリーミング、音声タグ、追加の自動検出言語。

gemini-3.1-flash-tts-preview の制約

  • 音声の不一致: プロンプトのトーンとコンテキストがスピーカーのプロフィールと一致しない場合(たとえば、若い女性のように話そうとする低い男性の声)、モデルの出力が選択したスピーカーと厳密に一致しないことがあります。プロンプトのコンテキストが音声と一致していることを確認します。
  • 長い出力: 数分を超える音声の場合、音声の品質と一貫性が低下する可能性があります。長いテキスト プロンプトは、小さなチャンクに分割することをおすすめします。
  • テキスト トークンが返されることがある: モデルが音声トークンではなくテキスト トークンを返すことがあり、リクエストが 500 エラーで失敗します。これは、リクエストのわずかな割合でランダムに発生するため、アプリに再試行ロジックを実装する必要があります。
  • 分類器の誤拒否: 曖昧なプロンプトは音声合成分類器で失敗し、リクエストが拒否される(PROHIBITED_CONTENT)か、モデルがスタイル指示を読み上げる可能性があります。これを回避するには、プロンプトの先頭に明確なプリアンブル(Audio Profile や Director's Notes など)を含む構造化プロンプトを使用します。



サポートされている音声と言語

Gemini TTS モデルはテキスト入力を受け取り、音声出力を生成します。そのため、レスポンスは合成音声自体です。次のサブセクションでは、Gemini TTS モデルが「話す」(または応答する)ことができる、サポートされている音声と言語の一覧を示します。

音声は多言語対応です。つまり、同じ音声を使用して、サポートされている任意の言語で音声を生成できます。たとえば、音声を Kore に設定し、スペイン語、ヒンディー語、ベトナム語で一連のテキスト プロンプトを送信できます。レスポンスはすべて Kore の音声ですが、言語はそれぞれ異なります。

音声名

Gemini TTS モデルは、それぞれに特徴のある 30 種類の合成 HD 音声をサポートしています。以下のセクションを開くと、レスポンス音声オプションのリストを表示し、各音声のデモを聴くことができます。

言語

Gemini TTS モデルは、テキスト プロンプトで次の言語を自動的に検出できます。生成される音声はその言語になります。

必要に応じて、音声構成で言語コードを明示的に設定することもできます。

すべての音声生成モデルでサポートされている言語
言語 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 ヘブライ語 he
ビルマ語 ミャンマー語(ビルマ語) ハンガリー語 hu
カタロニア語 ca アイスランド語 =
セブアノ語 ceb ジャワ語 jv
中国語(標準語) cmn カンナダ語 kn
クロアチア語 時間 コンカニ語 kok
チェコ語 cs ラオ語 lo
デンマーク語 da ラテン文字 la
エストニア語 et ラトビア語 lv
リトアニア語 lt ルクセンブルク語 lb
マケドニア語 mk マイティリー語 mai
マラガシ語 mg マレー語 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 アシスタントの機能

その他の機能を試す

コンテンツ生成を制御する方法を学習する

Google AI Studio を使用して、プロンプトとモデル構成をテストしたり、生成されたコード スニペットを取得したりすることもできます。

サポートされているモデルの詳細

さまざまなユースケースで使用できるモデル、割り当て、料金について確認する。


Firebase AI Logic の使用感に関するフィードバックを送信する