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 モデルを使用して、指定されたテキストから音声を生成できます。

単一の話者による音声を生成する

このサンプルを試す前に、このガイドの始める前にのセクションを完了して、プロジェクトとアプリを設定してください。
このセクションでは、選択した 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 のメソッドは 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: [ResponseModality.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);

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

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

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

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

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

Unity


using Firebase.AI;

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

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

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

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

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

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

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

複数の話者による音声を生成する

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

テキスト内の話者ごとに異なる音声を使用するようにモデルを構成できます。これは、会話や会話の音声の生成に役立ちます。

  1. スピーカー名(プロンプトで使用)を特定のレスポンス音声名Kore など)にマッピングする MultiSpeakerVoiceConfig を作成します。

    マルチスピーカー構成は、2 つのスピーカーのみをサポートします。

  2. GenerationConfig に以下を含めます。

    • responseModalities を設定して AUDIO を含めます。

    • 次のように SpeechConfig を構成します。

      • (必須) MultiSpeakerVoiceConfig を渡します。

      • (省略可) 言語コード
        言語を指定しない場合、Gemini TTS モデルはプロンプト内の言語を自動的に検出できます。

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

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

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

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

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

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

Unity


using Firebase.AI;

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

var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);

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

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

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

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

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

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

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

レスポンスをストリーミングする

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

音声ファイル全体が完了するのを待つのではなく、生成された音声レスポンスをストリーミングすることで、インタラクションを高速化し、レイテンシを短縮できます。

生成された音声のストリーミングは、単一話者構成と複数話者構成の両方でサポートされています。Gemini 3.x TTS モデルを使用する場合にのみサポートされます。

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

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

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

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

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

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

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

Unity


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

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

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

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

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

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

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

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

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



プロンプトで音声出力を制御する

特定のプロンプト技術を使用すると、生成される音声のトーン、ペース、スタイルに影響を与えることができます。

プロンプトの構造音声タグに関する次のサブセクションでは、概要レベルのガイダンスについて説明します。詳細なガイダンスについては、こちらのプロンプト ガイドをご覧ください。

プロンプトの構造

最適な結果を得るには、次のコンポーネントを使用してプロンプトを構成します。

  • Audio Profile: 話者のペルソナ、核となるアイデンティティ、アーキタイプ(A warm, professional narrator など)を説明します。

  • Scene: 環境と感情的な雰囲気(In a quiet libraryAmidst 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 ProfileDirector'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-USen-GBen-AUen-IN
  • フランス語: fr-FRfr-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-USes-ES
  • タミル語: ta-IN
  • テルグ語: te-IN
  • タイ語: th-TH
  • トルコ語: tr-TR
  • ベトナム語: vi-VN



Google アシスタントの機能

その他の機能を試す

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

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

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

さまざまなユースケースで利用可能なモデルとその割り当て料金について学習します。


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