Gemini TTS モデル(gemini-3.8-flash-tts または gemini-3.8-flash-lite-tts)を使用すると、テキストから自然で表現力豊かな音声(オーディオ)を合成できます。Firebase AI Logic を使用すると、モバイルアプリまたはウェブアプリ(Apple(Swift)、Android(Kotlin / Java)、ウェブ(JavaScript)、Flutter(Dart)、Unity アプリなど)から直接このリクエストを送信できます。
テキスト読み上げ(TTS)生成は制御可能です。つまり、音声に合成する正確なテキストを指定しながら、構造化されたメタデータとインライン音声タグを使用して、感情、ペース、話者の声、笑い声やため息などの音声以外の音などの配信をガイドできます。TTS は、音声文字変換(音声入力)の逆と考えることができます。
この機能を使用すると、次のような機能を構築できます。
- インタラクティブなストーリーテリングとオーディオブック: 長編のストーリーやロールプレイング ゲームをナレーションします。キャラクターは声を切り替え、重複するバックチャネルで互いに反応し、感情的な表現(サスペンスでささやいたり、ジョークで笑ったり)を調整します。
- 低レイテンシの音声エージェントとアシスタント: LLM からテキストが届くとすぐに合成音声をストリーミングし、会話のターン全体で一貫した音声ペルソナを維持します。
- 多言語コンテンツ リーダーと言語チューター: 130 以上の言語と地域のアクセントで記事、レシピ、学習教材を読み上げたり、1 つの会話内で言語をシームレスに切り替えたりできます。
このガイドでは、単一話者と複数話者の音声を生成する方法、音声レスポンスをストリーミングする方法、SpeechMetadata タグとインラインタグを使用して音声配信を指示する方法、事前構築済み、ライブラリ、カスタム音声から選択する方法について説明します。
単一話者のコードに切り替え 複数話者のコードに切り替え ストリーミング コードに切り替え
TTS と Live API の比較
テキスト読み上げ(TTS)モデルと Live API モデルはどちらも、さまざまなレスポンス音声と言語に構成できる低レイテンシの音声生成モデルです。ただし、ユースケースは大きく異なります。
テキスト読み上げ(TTS)生成は、一方向のリクエスト / レスポンス型のインタラクション(テキスト入力、音声出力)です。ポッドキャストのナレーション、オーディオブック、記事の読み上げなど、スタイルと音声をきめ細かく制御して、提供されたテキストを正確に読み上げる必要があるシナリオに合わせて調整されています。
Live API 世代は、リアルタイムの音声会話(音声入力、音声出力)の双方向ストリーミングをサポートしています。モデルが返す適切な音声を決定する動的な会話コンテキストに優れています。最新の Live API モデルは、動画と画像の入力もサポートしています。
始める前に
|
Gemini API プロバイダをクリックして、このページでプロバイダ固有のコンテンツとコードを表示します。 |
まだ完了していない場合は、スタートガイドに沿って、Firebase プロジェクトの設定、アプリと Firebase の連携、SDK の追加、選択した Gemini API プロバイダのバックエンド サービスの初期化、GenerativeModel インスタンスの作成を行います。
プロンプトのテストと反復処理には、Google AI Studio を使用することをおすすめします。
この機能をサポートするモデル
gemini-3.8-flash-ttsgemini-3.8-flash-lite-tts
TTS モデルの比較
どちらの Gemini 3.x TTS モデルも、同じリクエスト スキーマとプロンプト形式を使用します。ただし、各モデルを使用するタイミングにはいくつかの違いがあります。
| 機能またはワークロード | gemini-3.8-flash-tts |
gemini-3.8-flash-lite-tts |
|---|---|---|
| 主な強み | スタジオ品質の音声忠実度、演技のニュアンス、幅広い方言のサポート | 高スループット、低レイテンシ、費用対効果 |
| 最適なユースケース | オーディオブック、スタジオ ナレーション、複雑なマルチスピーカーの会話、頻繁な音声バーストタグ、難しい発音、地域の方言 | 大量の本番環境、リアルタイム音声エージェントのカスケード、読み上げ UI 機能、日常的な単一話者の音声 |
| サポートされている言語 | 132 言語 | 103 言語 |
テキストから音声を生成する
テキスト入力から、1 人のスピーカーの音声または 2 人のスピーカーの会話を、完全な WAV ファイル(generateContent)または低レイテンシの未加工の PCM 音声ストリーム(generateContentStream)として生成できます。
1 人の話者による音声を生成する
|
このサンプルを試す前に、このガイドの始める前にセクションを完了して、プロジェクトとアプリを設定してください。 このセクションでは、選択した Gemini API プロバイダのボタンをクリックして、このページにプロバイダ固有のコンテンツを表示します。 |
単一話者の音声を生成する方法は次のとおりです。
GenerationConfigで、responseModalitiesをAUDIOに設定し、次のようにSpeechConfigを構成します。(必須)音声名または ID。これは、
Koreなどの事前構築済みの音声、拡張音声ライブラリの音声 ID、またはカスタム音声のvoice_.../voicekey_...ID です。(省略可)BCP-47 言語コード。省略すると、モデルは言語を自動的に検出します。
次の内容の
TextPartを作成します。(必須)読み上げる文字起こしテキスト。
(省略可)
styleの説明を含むSpeechMetadata(例:"cheerful and friendly")。
generateContentを呼び出します。デフォルトでは、単項リクエストは、レスポンスのインライン データ部分に完全な WAV(audio/wav)音声ファイル(16 ビット リニア PCM、24 kHz、モノラル、標準の 44 バイト RIFF ヘッダー付き)を返します。
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.8-flash-tts",
generationConfig: config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
let prompt = TextPart(
"Have a wonderful day!",
speechMetadata: SpeechMetadata(style: "cheerful and friendly")
)
// Call `generateContent` to generate the speech output.
let response = try await model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let wavData = part.data // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
let mimeType = part.mimeType // for example: "audio/wav"
print("Received audio data with MIME type: \(mimeType)")
// Play the WAV audio data using your own playback helper (for example, with `AVAudioPlayer(data: wavData)`).
playAudio(data: wavData)
}
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.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "gemini-3.8-flash-tts",
generationConfig = config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
val prompt = content {
text(
text = "Have a wonderful day!",
speechMetadata = SpeechMetadata(style = "cheerful and friendly")
)
}
// Call `generateContent` to generate the speech output.
val response = model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val wavData = part.inlineData // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData)
}
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.8-flash-tts", config);
// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
Content content = new Content.Builder()
.addText("Have a wonderful day!", new SpeechMetadata(null, "cheerful and friendly"))
.build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output.
// Extract the WAV 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[] wavData = ((InlineDataPart) part).getInlineData(); // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData);
}
}
@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.8-flash-tts",
generationConfig
});
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
const prompt = [
{
type: "text",
text: "Have a wonderful day!",
speechMetadata: { style: "cheerful and friendly" }
}
];
// Call `generateContent` to generate the speech output.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the WAV audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const wavBase64 = inlineDataParts[0].inlineData.data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Decode base64 to ArrayBuffer
const wavBuffer = Uint8Array.from(atob(wavBase64), c => c.charCodeAt(0)).buffer;
// The response is a complete WAV file, so the Web Audio API can decode and play it directly.
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(wavBuffer);
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start();
}
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.8-flash-tts',
generationConfig: config,
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
final prompt = Content.multi([
TextPart(
'Have a wonderful day!',
speechMetadata: SpeechMetadata(style: 'cheerful and friendly'),
),
]);
// Call `generateContent` to generate the speech output.
final response = await model.generateContent([prompt]);
// Extract the WAV 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 wavData = part.bytes; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Play the WAV audio data using your preferred audio player or helper (which you'll need to implement).
await playAudio(wavData);
}
Unity
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 language code.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore", "en-US")
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.8-flash-tts",
generationConfig: config
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
var prompt = new ModelContent(
new ModelContent.TextPart(
"Have a wonderful day!",
new SpeechMetadata(speaker: null, style: "cheerful and friendly")
)
);
// Call `GenerateContentAsync` to generate the speech output.
var response = await model.GenerateContentAsync(prompt);
// Extract the WAV 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[] wavData = inlineData.Data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
PlayAudio(wavData);
}
}
}
複数の話者による音声を生成する
|
このサンプルを試す前に、このガイドの始める前にセクションを完了して、プロジェクトとアプリを設定してください。 このセクションでは、選択した Gemini API プロバイダのボタンをクリックして、このページにプロバイダ固有のコンテンツを表示します。 |
各話者に異なる音声を割り当て、会話の各行を独自の TextPart として渡すことで、1 つのリクエストで自然な 2 人の会話を生成できます。
2 つの話者名(
"Joe"と"Jane"など)をSpeakerVoiceConfigの音声にマッピングするMultiSpeakerVoiceConfigを作成します。GenerationConfigで、responseModalitiesをAUDIOに設定し、MultiSpeakerVoiceConfig(およびオプションのlanguageCode)をSpeechConfigに渡します。TextPartオブジェクトの配列またはリストを指定します。具体的には、会話のターンごとに 1 つのTextPartを指定します。すべてのTextPartで、SpeechMetadataを次のように設定します。- (必須)
MultiSpeakerVoiceConfigで定義されているスピーカー名のいずれかに一致するspeaker。 - (省略可)
styleの説明(例:"cheerful and friendly")。
- (必須)
generateContentを呼び出します。モデルは会話全体を合成し、完全な WAV(audio/wav)音声ファイルを返します。
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.8-flash-tts",
generationConfig: config
)
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
let prompt: [any PartsRepresentable] = [
TextPart(
"How's it going today, Jane?",
speechMetadata: SpeechMetadata(speaker: "Joe", style: "cheerful and friendly")
),
TextPart(
"Not too bad, how about you?",
speechMetadata: SpeechMetadata(speaker: "Jane", style: "calm and relaxed")
)
]
// Call `generateContent` to generate the multi-speaker speech output.
let response = try await model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let wavData = part.data // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
let mimeType = part.mimeType // for example: "audio/wav"
print("Received audio data with MIME type: \(mimeType)")
// Play the WAV audio data using your own playback helper (for example, with `AVAudioPlayer(data: wavData)`).
playAudio(data: wavData)
}
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.8-flash-tts",
generationConfig = config
)
// Provide one text part per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
val prompt = content {
text(
text = "How's it going today, Jane?",
speechMetadata = SpeechMetadata(speaker = "Joe", style = "cheerful and friendly")
)
text(
text = "Not too bad, how about you?",
speechMetadata = SpeechMetadata(speaker = "Jane", style = "calm and relaxed")
)
}
// Call `generateContent` to generate the multi-speaker speech output.
val response = model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val wavData = part.inlineData // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData)
}
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, "en-US");
// 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.8-flash-tts", config);
// Use the `GenerativeModelFutures` Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide one text part per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
Content content = new Content.Builder()
.addText(
"How's it going today, Jane?",
new SpeechMetadata("Joe", "cheerful and friendly"))
.addText(
"Not too bad, how about you?",
new SpeechMetadata("Jane", "calm and relaxed"))
.build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the multi-speaker speech output.
// Extract the WAV 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[] wavData = ((InlineDataPart) part).getInlineData(); // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData);
}
}
@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.8-flash-tts",
generationConfig
});
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `speechMetadata`.
const prompt = [
{
type: "text",
text: "How's it going today, Jane?",
speechMetadata: { speaker: "Joe", style: "cheerful and friendly" }
},
{
type: "text",
text: "Not too bad, how about you?",
speechMetadata: { speaker: "Jane", style: "calm and relaxed" }
}
];
// Call `generateContent` to generate the multi-speaker speech output.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the WAV audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const wavBase64 = inlineDataParts[0].inlineData.data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Decode base64 to ArrayBuffer
const wavBuffer = Uint8Array.from(atob(wavBase64), c => c.charCodeAt(0)).buffer;
// The response is a complete WAV file, so the Web Audio API can decode and play it directly.
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(wavBuffer);
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start();
}
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.8-flash-tts',
generationConfig: config,
);
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
final prompt = Content.multi([
TextPart(
"How's it going today, Jane?",
speechMetadata: SpeechMetadata(speaker: 'Joe', style: 'cheerful and friendly'),
),
TextPart(
'Not too bad, how about you?',
speechMetadata: SpeechMetadata(speaker: 'Jane', style: 'calm and relaxed'),
),
]);
// Call `generateContent` to generate the multi-speaker speech output.
final response = await model.generateContent([prompt]);
// Extract the WAV 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 wavData = part.bytes; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Play the WAV audio data using your preferred audio player or helper (which you'll need to implement).
await playAudio(wavData);
}
Unity
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// 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, "en-US");
// Set `responseModalities` to include `Audio`.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: multiSpeechConfig
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.8-flash-tts",
generationConfig: config
);
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
var prompt = new ModelContent(
new ModelContent.TextPart(
"How's it going today, Jane?",
new SpeechMetadata(speaker: "Joe", style: "cheerful and friendly")
),
new ModelContent.TextPart(
"Not too bad, how about you?",
new SpeechMetadata(speaker: "Jane", style: "calm and relaxed")
)
);
// Call `GenerateContentAsync` to generate the multi-speaker speech output.
var response = await model.GenerateContentAsync(prompt);
// Extract the WAV 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[] wavData = inlineData.Data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
PlayAudio(wavData);
}
}
}
レスポンスをストリーミングする
|
このサンプルを試す前に、このガイドの始める前にセクションを完了して、プロジェクトとアプリを設定してください。 このセクションでは、選択した Gemini API プロバイダのボタンをクリックして、このページにプロバイダ固有のコンテンツを表示します。 |
最初の音声までの時間(TTFA)を短縮し、リアルタイム再生を実現するには、クリップ全体が完了するのを待つのではなく、生成された音声レスポンスをストリーミングします。ストリーミングは、シングルスピーカー構成とマルチスピーカー構成の両方で機能します。
音声をストリーミングするには、generateContent ではなく generateContentStream を呼び出します。単項リクエスト(WAV ファイルを返す)とは異なり、ストリーミング リクエストはヘッダーなしの未加工の 16 ビット符号付きリトル エンディアン PCM チャンク(audio/l16、24 kHz、モノラル)を返します。そのため、各チャンクを音声出力バッファに直接追加できます。
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.8-flash-tts",
generationConfig: config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
let prompt = TextPart(
"Tell me a story about a brave knight.",
speechMetadata: SpeechMetadata(style: "warm, engaging audiobook narrator")
)
// Call `generateContentStream` to stream the speech output as it is generated.
let responseStream = try model.generateContentStream(prompt)
// Extract the raw PCM audio chunks and queue them for playback:
for try await chunk in responseStream {
for part in chunk.inlineDataParts {
let pcmChunk = part.data // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
appendAudioChunk(pcmChunk)
}
}
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.8-flash-tts",
generationConfig = config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
val prompt = content {
text(
text = "Tell me a story about a brave knight.",
speechMetadata = SpeechMetadata(style = "warm, engaging audiobook narrator")
)
}
// Call `generateContentStream` to stream the speech output as it is generated.
// Extract the raw PCM audio chunks and queue them for playback.
model.generateContentStream(prompt).collect { chunk ->
val part = chunk.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val pcmChunk = part.inlineData // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts", config);
// Use the `GenerativeModelFutures` Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
Content content = new Content.Builder()
.addText(
"Tell me a story about a brave knight.",
new SpeechMetadata(null, "warm, engaging audiobook narrator"))
.build();
// Call `generateContentStream` to stream the speech output as it is generated.
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(content);
// Extract the raw PCM audio chunks and queue them for playback.
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(); // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts",
generationConfig
});
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
const prompt = [
{
type: "text",
text: "Tell me a story about a brave knight.",
speechMetadata: { style: "warm, engaging audiobook narrator" }
}
];
// Call `generateContentStream` to stream the speech output as it is generated.
const result = await model.generateContentStream(prompt);
// Extract the raw PCM audio chunks and queue them for playback:
const playbackQueue = [];
for await (const chunk of result.stream) {
const inlineDataParts = chunk.inlineDataParts();
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Headerless 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.
// In a real app, start playing chunks as they arrive (rather than waiting for
// the whole stream to finish) to get the low-latency benefit of streaming.
playbackQueue.push(pcmBuffer);
}
}
// To play back an array of PCM buffers in sequence, pass them to your playback helper (which you'll need to write).
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.8-flash-tts',
generationConfig: config,
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
final prompt = Content.multi([
TextPart(
'Tell me a story about a brave knight.',
speechMetadata: SpeechMetadata(style: 'warm, engaging audiobook narrator'),
),
]);
// Call `generateContentStream` to stream the speech output as it is generated.
final responseStream = model.generateContentStream([prompt]);
// Extract the raw PCM audio chunks and queue them for playback:
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; // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts",
generationConfig: config
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
var prompt = new ModelContent(
new ModelContent.TextPart(
"Tell me a story about a brave knight.",
new SpeechMetadata(speaker: null, style: "warm, engaging audiobook narrator")
)
);
// Call `GenerateContentStreamAsync` to stream the speech output as it is generated.
var responseStream = model.GenerateContentStreamAsync(prompt);
// Extract the raw PCM audio chunks and queue them for playback:
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; // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
AppendAudioChunk(pcmChunk);
}
}
メタデータとインラインタグを使用して音声出力を制御する
Gemini 3.x TTS モデルは、各 TextPart 内の text を、読み上げられる逐語的な音声文字変換として厳密に扱います。テキスト文字列内にナラティブ指示("Say cheerfully:" など)を記述しないでください。モデルがそれらの単語を読み上げる可能性があります。
次の手法を使用して、ボーカル パフォーマンスを指示できます。
ターンレベルの style とインラインの音声タグ
パフォーマンス ディレクティブをスコープ別に SpeechMetadata とインライン山かっこタグ(<...>)に分割します。
| スコープ | 設置場所 | 制御対象 | 例 |
|---|---|---|---|
|
ターンレベル (ターン全体で持続) |
SpeechMetadata.style
|
感情、ペルソナ、トーン、抑揚、ピッチ、全体的な話す速度 |
"cheerful and friendly","whispered, nervous","speaking rapidly","out of breath","sarcastic"
|
|
ポイントインタイム (文中の特定の瞬間にローカライズ) |
<...> を使用した TextPart テキストのインライン |
音声以外の人の声、息遣い、一時停止、瞬間的な話し方の変化 |
"Wait... <short pause> did you hear that? <gasp> Someone's at the door."
|
ペース、間、ピッチ、強調
句読点と省略記号: 音声文字変換でカンマ、ダッシュ(
--)、省略記号(...)を使用して、自然な言い回しや言いよどみを作成します。明示的な一時停止タグ: 話者が一時停止する正確な位置に
<short pause>または<long pause>をインラインで挿入します。Hold on, let me think... <short pause> Alright, I've got it.発話速度とピッチ:
SpeechMetadataでstyleを設定して、ターン全体のペース、ピッチ、抑揚を制御します(例:"speaking rapidly and excitedly"、"speaking slowly"、"monotone and flat")。モノローグの途中で感情やペースが変化する場合は、スクリプトを別々のTextPartターンに分割し、それぞれに独自のstyleを設定します。単語の強調: 音声文字変換で特定の単語を強調するには、その単語を大文字にします。
It was a VERY long day <sigh> ... nobody listens anymore.
ボーカル バーストと非音声
山かっこ(<...>)を使用して、音声が発生する正確な単語の境界に、音声以外の人の発声をインラインで挿入します。非音声の効果音ではなく、人間の声を使用します。推奨されるタグは次のとおりです。
<argh> |
<exhales> |
<heavy breath> |
<scream> |
<snort> |
<breath> |
<gasp> |
<hiss> |
<short pause> |
<sob> |
<cackle> |
<giggle> |
<laugh> /<laughter> |
<shout> |
<throat-clearing> |
<cheer> |
<groan> |
<long pause> |
<shriek> |
<tsk> |
<chuckle> /<chuckles> |
<growl> |
<moan> |
<sigh> /<sighs> |
<whimper> |
<cough> |
<grr> |
<pant> |
<sneeze> |
<whispers> /<whispering> |
<cry> |
<grunt> |
<pff> /<phew> |
<snicker> |
<yawn> |
相槌と音声の重複
複数の話者による会話では、アクティブな話者の音声文字変換内で、聞き手の短い反応をパイプ文字(|reaction|)で囲むことができます。アクティブでない話者は、別のターンを必要とせずに、その時点で自然に割り込みます。
短いリスナー バックチャンネル:
- ターン 1(
speaker: "Joe"):"So the launch is Thursday |oh hmm| Are we actually ready?" - ターン 2(
speaker: "Jane"):"Ready enough |oh really?| The last blocker cleared this morning."
- ターン 1(
重複する音声: 複数のパイプ セグメントを使用して、同時発話をシミュレートできます(
gemini-3.8-flash-ttsで最適に機能します)。次に例を示します。- ターン 1(
speaker: "Joe"):"Let's surprise him on three |ok| ready?" - ターン 2(
speaker: "Jane"):"one. two. three. |happy| happy |birthday| birthday!"
- ターン 1(
一貫性を保つためのベスト プラクティス
まず
styleなしでテストし、簡潔なstyleの調整を追加する: ほとんどのリクエストは、styleフィールドが空でも自然に聞こえます。ターンに特定の配信調整が必要な場合にのみ、短いstyleフレーズ("casual, friendly"や"reflective and awe-inspired"など)を追加します。一貫したベースラインが必要な場合は、ターン間で同じ短い文字列を再利用します。自然な話し言葉の音声文字変換を作成する: 会話の短縮形や自然な言いよどみ(
"Oh, uh, yeah I think... hm, that's interesting"など)を音声文字変換テキストに直接含めます。以前の
[Audio Profile]ブロックとメタ指示を避ける: 長いペルソナ段落、[Director's Notes]ブロック、"maintain identical timbre"などのメタ指示は、音声ドリフトを増加させます。代わりに、拡張音声ライブラリから一致する音声を選択するか、音声デザインで永続的なキャラクター音声を作成します。styleで不変の音声特性をオーバーライドしようとしないでください:SpeechMetadata.styleを使用して、音声の年齢、性別、永続的なアクセントを変更しないでください。代わりに、そのような特性を持つ音声を選択または設計します。
サポート対象の音声
Gemini 3.x TTS モデルは、音声を指定する 3 つの方法をサポートしています。
すべての音声は多言語対応です。つまり、同じ音声を使用して、サポートされている言語のいずれかで音声を生成しながら、一貫した話者のアイデンティティを維持できます。たとえば、音声を事前構築済みの Kore 音声に設定し、スペイン語、ヒンディー語、ベトナム語でプロンプトを送信すると、レスポンスはすべて、それぞれの言語の Kore 音声を使用します。30 個のコア事前構築済み音声は汎用の多言語音声ですが、拡張音声ライブラリの音声とカスタム音声は、プライマリ ロケールまたはリージョンのアクセントに固定されています。つまり、他の言語を話すことはできますが、メインの言語 / 地域で最も自然に聞こえます。
コアの事前構築済み音声
Gemini TTS モデルは、30 種類のコア事前構築済み音声(Kore、Puck、Zephyr、Charon、Fenrir など)をサポートしています。各音声には、それぞれ異なる音声特性があります。SpeechConfig で音声名を渡します(このページの前の単一話者と複数話者の例を参照)。
拡張音声ライブラリのプリセット音声
30 種類の事前構築済み音声に加えて、拡張音声ライブラリには、さまざまな言語、地域アクセント、年齢層、キャラクター ペルソナ、ユースケース(オーディオブック、カスタマー サポート エージェント、ニュースリーダーなど)にわたる 2,000 種類以上の厳選されたプリセット音声が用意されています。
拡張音声ライブラリの音声をアプリで使用する方法は次のとおりです。
次のいずれかの方法で音声をブラウジングしてプレビューします。
Google AI Studio または Agent Studio を使用して、音声
idを取得します。Voices API の
listメソッド(type=prebuiltとオプションのsearchクエリを含むListVoices)をクエリして、音声idを取得します。詳しくは、Gemini Developer API のドキュメントまたは Agent Platform Gemini API (formerly Vertex AI) のドキュメントをご覧ください。
ライブラリ音声の
id文字列をSpeechConfigの音声名として渡します(このページの前の単一話者の例と同様)。
カスタム音声: 音声デザインとボイス レプリケーション
Gemini 3.x TTS モデルは、次のいずれかのオプションを使用したカスタム音声もサポートしています。
音声デザイン(プレビュー): 話者の年齢、声色、アクセント、ペルソナの自然言語による説明から、独自のカスタム音声を生成します(参照音声は必要ありません)。保存されている音声 ID(
voice_...)を返します。ボイス レプリケーション(プレビュー): 参照録音と音声による同意録音から、話者の声、トーン、リズムを複製します。プロジェクトに保存された音声 ID(
voice_...)またはステートレスなアプリ管理のボイス レプリケーション キー(voicekey_...)を返します。
Firebase AI Logic アプリでカスタム音声を使用する
カスタム音声の作成と管理は、管理オペレーションまたはサーバーサイド オペレーションであるため、Firebase AI Logic クライアント SDK は音声管理エンドポイント(CreateVoice、ListVoices、DeleteVoice)を直接公開しません。
代わりに、カスタム音声を使用するには、次の操作を行う必要があります。
次のいずれかのオプションを使用して、カスタム音声を 1 回作成します。
Google AI Studio または Agent Studio を使用して、
voice_<id>またはvoicekey_<id>識別子を取得します。Voices API を使用して、
voice_<id>またはvoicekey_<id>識別子を取得します。詳細については、選択した Gemini API プロバイダのドキュメントをご覧ください。Gemini Developer API: 音声生成
Agent Platform Gemini API (formerly Vertex AI): 音声デザインとボイス レプリケーション
SpeechConfigの音声名としてvoice_<id>またはvoicekey_<id>文字列を渡します(このページで前述した単一話者の例と同様)。
カスタム音声を使用する場合は、次の要件に注意してください。
ロケーション(Agent Platform Gemini API (formerly Vertex AI)): カスタム音声(
voice_...とvoicekey_...)は、globalロケーション(Firebase AI Logic を使用する場合のデフォルトの場所)でのみサポートされています。単一スピーカーのリクエスト:
MultiSpeakerVoiceConfigは、コアの事前構築済み音声のみをサポートしています。複数のキャラクターの会話でカスタム設計または複製された音声を使用するには、各キャラクターのターンを個別の単一話者リクエストで合成します。保持と有効期限: 保存されたカスタム音声(
voice_...)は、1 年間使用されないと有効期限が切れます(合成リクエストごとに 1 年間の保持タイマーがリセットされます)。ステートレス ボイス レプリケーション キー(voicekey_...)は、作成から 7 日後に有効期限が切れます。
サポートされている言語
Gemini 3.x TTS モデルは、入力テキストから言語を自動的に検出します。これには、複数の話者による会話でプロンプトがターン間で言語を切り替える場合も含まれます。
- Gemini 3.8 Flash TTS(
gemini-3.8-flash-tts): 132 言語をサポートしています。 - Gemini 3.8 Flash‑Lite TTS(
gemini-3.8-flash-lite-tts): 103 言語をサポートしています。
(省略可)言語コードを明示的に設定する
音声合成を特定のロケールに明示的に制限する場合は、SpeechConfig で BCP-47 languageCode を渡します。
音声出力形式
InlineDataPart で返されるデフォルトの音声形式は、単項リクエストとストリーミング リクエストのどちらを行うかによって異なります。
| リクエスト メソッド | デフォルトで返される MIME タイプ | オーディオ形式の詳細 |
|---|---|---|
|
単項 ( generateContent)
|
audio/wav
|
標準の 44 バイト RIFF ヘッダーを含む完全な WAV ファイル(16 ビット リニア PCM、24 kHz、モノラル、リトル エンディアン)。
標準のプラットフォーム オーディオ プレーヤー(Apple プラットフォームの |
|
ストリーミング ( generateContentStream)
|
audio/l16
|
ヘッダーなしの RAW 16 ビット符号付きリトル エンディアン PCM チャンク(24 kHz、モノラル)。 チャンクごとのファイル ヘッダーなしで、低レイテンシのバッファ キューイングと連結を行うように設計されています。 |
制限事項と要件
Gemini 3.x TTS モデルを使用する場合は、次の制限と要件に注意してください。
テキストのみの入力、音声のみの出力: TTS モデルはテキスト入力(
TextPart)のみを受け入れ、responseModalitiesをAUDIOに設定する必要があります。逐語的な合成のみ: モデルは、提供された文字起こしを逐語的に読み上げ、会話形式のテキスト返信は生成しません。
トークンの上限: リクエストあたりの最大入力は 8,192 トークン、最大出力は 16,384 トークンです。
マルチスピーカーの上限:
MultiSpeakerVoiceConfigには 2 つのスピーカーが必要で、コアの事前構築済み音声のみがサポートされています。マルチスピーカー リクエストのすべてのTextPartには、構成されたスピーカーのいずれかに一致するSpeechMetadata.speakerを含める必要があります。サポートされていないパラメータとメソッド:
- Firebase AI Logic SDK は、デフォルトの音声出力形式をオーバーライドするための
GenerationConfigでのresponseFormatの設定をまだサポートしていません。 systemInstruction、temperature、topP、topK、candidateCount、presencePenalty、frequencyPenaltyの設定はサポートされていません。設定すると、リクエストが失敗し、400 INVALID_ARGUMENTエラーが発生します。- TTS モデルでは
countTokensの呼び出しはサポートされていません(トークン数はレスポンスのusageMetadataで返されます)。
- Firebase AI Logic SDK は、デフォルトの音声出力形式をオーバーライドするための
ロケーション(Agent Platform Gemini API (formerly Vertex AI)): カスタム音声(
voice_...とvoicekey_...)には、globalロケーションが必要です(Firebase AI Logic を使用する場合のデフォルトの場所)。
gemini-3.1-flash-tts-preview からの移行
gemini-3.8-flash-tts と gemini-3.8-flash-lite-tts はどちらも同じリクエスト構造を使用します。モデル比較表を確認して、ワークロードに最適な代替モデルを選択し、次のようにコードを更新します。
| 分野 |
gemini-3.1-flash-tts-preview(レガシー)
|
gemini-3.8-flash-tts、gemini-3.8-flash-lite-tts
|
|---|---|---|
| 配信スタイルと方向性 |
プロンプト テキストに埋め込まれている。例:"Say cheerfully: ..."、[Audio Profile]、[Director's Notes]
|
各 TextPart の SpeechMetadata(style: "...") で渡されます。
|
| 複数の話者による会話 |
インライン "Speaker: ..." 接頭辞を含む単一のテキスト文字列
|
会話ターンごとに 1 つの TextPart。各 TextPart に SpeechMetadata(speaker: "...", style: "...")。 |
| インライン音声タグ |
角かっこ。例: [sigh] または [laughs]
|
山かっこ。例: <sigh>、<laugh>、<short pause>
|
デフォルトの単項音声形式(generateContent) |
ヘッダーなしの RAW 16 ビット PCM(audio/pcm、24 kHz、モノラル) |
完全な WAV ファイル(audio/wav、16 ビット PCM、24 kHz、モノラル、44 バイトの RIFF ヘッダー付き)
ストリーミング( |
| システム指示、温度、top-P、top-K | 無視されました |
400 INVALID_ARGUMENT エラーで拒否されました。これらのパラメータをモデル構成から削除します。 |
移行チェックリスト
Firebase AI Logic SDK の最新バージョンにアップグレードし、モデル名を
gemini-3.8-flash-ttsまたはgemini-3.8-flash-lite-ttsに更新します。スタイル指示を
SpeechMetadata.styleに移動する:"Say cheerfully:"接頭辞、[Audio Profile]、[Scene]、[Director's Notes]ブロックをプロンプト文字列から削除して、モデルが読み上げないようにします。代わりに、SpeechMetadata.styleで簡潔なスタイル説明を渡します。複数の話者のスクリプトを個別の
TextPartターンに分割する:"Joe: ... \n Jane: ..."テキスト ブロックをTextPartオブジェクトの配列 / リストに置き換えます。各ターンでSpeechMetadata.speakerを設定します。[...]タグを<...>タグに変換する: 角かっこで囲まれた音声タグ([whispers]、[sighs]、[laughs]など)を、山かっこで囲まれた音声タグ(<whispers>、<sigh>、<laugh>、<short pause>など)に置き換えます。単項音声再生を更新する:
generateContentは、ヘッダーのない未加工の PCM ではなく、完全な WAV ファイル(44 バイトの RIFF ヘッダー付き)を返すようになりました。単項レスポンスに WAV ヘッダーを手動で追加するコードを削除します(または、未加工の PCM サンプルを Android のAudioTrackや Unity のAudioClipなどの低レベル バッファ API にフィードする場合は、44 バイトのヘッダーをスキップします)。サポートされていない構成パラメータを削除する: TTS
GenerativeModel構成からtemperature、topP、topK、candidateCount、presencePenalty、frequencyPenalty、systemInstructionを削除します。
Google アシスタントの機能
-
本番環境の準備について検討を開始します(本番環境チェックリストをご覧ください)。
- できるだけ早く Firebase App Check を適用して、未承認のクライアントによる不正使用から Gemini API を保護します。
- Firebase Remote Config またはサーバー プロンプト テンプレートを使用して、アプリの新しいバージョンをリリースすることなく、AI 機能の構成(モデル名など)をオンデマンドで変更できるようにします。
その他の機能を試す
- マルチターンの会話(チャット)を構築する。
- テキストのみのプロンプトからテキストを生成する。
- テキスト プロンプトとマルチモーダル プロンプトの両方から構造化出力(JSON など)を生成します。
- テキスト プロンプトとマルチモーダル プロンプトの両方から画像を生成して編集します。
- Gemini Live API を使用して入出力をストリーミングする(音声を含む)。
-
ツール(関数呼び出しや
Google Search またはGoogle Maps を使用したグラウンディングなど)を使用して、Gemini モデルをアプリの他の部分や外部システム、情報に接続します。
コンテンツ生成を制御する方法を学習する
- ベスト プラクティス、戦略、プロンプトの例など、プロンプト設計を理解する。
- 最大出力トークン、繰り返し出力トークンの確率など、モデル パラメータを構成します。
- 安全性の設定を使用して、有害と見なされる可能性のある回答が生成される可能性を調整します。
サポートされているモデルの詳細
さまざまなユースケースで使用できるモデル、割り当て、料金について確認する。Firebase AI Logic の使用感に関するフィードバックを送信する