Bạn có thể sử dụng mô hình TTS Gemini (gemini-3.8-flash-tts hoặc gemini-3.8-flash-lite-tts) để tổng hợp lời nói (âm thanh) tự nhiên, biểu cảm từ văn bản. Khi sử dụng Firebase AI Logic, bạn có thể đưa ra yêu cầu này
trực tiếp từ ứng dụng di động hoặc ứng dụng web (chẳng hạn như ứng dụng Apple (Swift), Android
(Kotlin/Java), Web (JavaScript), Flutter (Dart) hoặc Unity).
Tính năng tạo chuyển văn bản sang lời nói (TTS) có thể kiểm soát được, nghĩa là bạn cung cấp văn bản chính xác để tổng hợp thành lời nói, đồng thời hướng dẫn cách truyền tải (chẳng hạn như cảm xúc, tốc độ, giọng nói của người nói và âm thanh không phải lời nói như tiếng cười hoặc tiếng thở dài) bằng cách sử dụng siêu dữ liệu có cấu trúc và thẻ giọng nói cùng dòng. Bạn có thể coi TTS là ngược lại với bản chép lời (chuyển lời nói thành văn bản).
Với tính năng này, bạn có thể xây dựng các tính năng như:
- Kể chuyện và sách nói tương tác: Kể chuyện dài hoặc trò chơi nhập vai, trong đó các nhân vật chuyển đổi giọng nói, phản ứng với nhau bằng các kênh phản hồi chồng chéo và điều chỉnh cách thể hiện cảm xúc (như thì thầm khi hồi hộp hoặc cười khi nghe chuyện cười).
- Trợ lý và tác nhân thoại có độ trễ thấp: Phát trực tuyến lời nói tổng hợp ngay khi văn bản đến từ một LLM, duy trì giọng nói nhất quán trong suốt các lượt trò chuyện.
- Trình đọc nội dung đa ngôn ngữ và gia sư ngôn ngữ: Đọc to các bài viết, công thức nấu ăn hoặc tài liệu học tập bằng hơn 130 ngôn ngữ và giọng địa phương, hoặc chuyển đổi ngôn ngữ một cách mượt mà trong một cuộc trò chuyện.
Hướng dẫn này trình bày cách tạo lời nói của một người nói và nhiều người nói, truyền trực tuyến
phản hồi bằng âm thanh, điều hướng cách phát âm bằng SpeechMetadata và thẻ cùng dòng,
đồng thời chọn trong số các giọng nói tạo sẵn, giọng nói trong thư viện hoặc giọng nói tuỳ chỉnh.
Chuyển đến mã cho một người nói Chuyển đến mã cho nhiều người nói Chuyển đến mã cho tính năng phát trực tuyến
So sánh giữa TTS và Live API
Cả mô hình chuyển văn bản sang lời nói (TTS) và mô hình Live API đều là các mô hình tạo lời nói có độ trễ thấp, có thể được định cấu hình cho nhiều giọng nói và ngôn ngữ phản hồi. Tuy nhiên, chúng phục vụ các trường hợp sử dụng rất khác nhau.
Tạo tính năng chuyển văn bản sang lời nói (TTS) là một hoạt động tương tác một chiều, yêu cầu-phản hồi (văn bản vào, âm thanh ra). Mô hình này được điều chỉnh cho phù hợp với những trường hợp cần đọc chính xác văn bản được cung cấp, đồng thời có khả năng kiểm soát chi tiết phong cách và âm thanh, chẳng hạn như đọc podcast, sách nói hoặc đọc to bài viết.
Live API thế hệ hỗ trợ tính năng truyền trực tuyến hai chiều cho cuộc trò chuyện thoại theo thời gian thực (giọng nói vào, giọng nói ra). Mô hình này hoạt động hiệu quả trong các bối cảnh trò chuyện linh hoạt, trong đó mô hình quyết định lời nói phù hợp để trả về. Xin lưu ý rằng các mô hình Live API mới nhất cũng hỗ trợ dữ liệu đầu vào là video và hình ảnh.
Trước khi bắt đầu
|
Nhấp vào nhà cung cấp Gemini API của bạn để xem nội dung và mã dành riêng cho nhà cung cấp trên trang này. |
Nếu bạn chưa thực hiện, hãy hoàn tất
hướng dẫn bắt đầu sử dụng, trong đó mô tả cách
thiết lập dự án Firebase, kết nối ứng dụng với Firebase, thêm SDK,
khởi động dịch vụ phụ trợ cho nhà cung cấp Gemini API mà bạn chọn và
tạo một thực thể GenerativeModel.
Để thử nghiệm và lặp lại câu lệnh, bạn nên sử dụng Google AI Studio.
Các mô hình hỗ trợ tính năng này
gemini-3.8-flash-ttsgemini-3.8-flash-lite-tts
So sánh các mô hình TTS
Cả hai mô hình Gemini 3.x TTS đều có cùng giản đồ yêu cầu và định dạng câu lệnh. Tuy nhiên, sau đây là một số điểm khác biệt về thời điểm bạn có thể sử dụng từng mô hình.
| Tính năng hoặc khối lượng công việc | gemini-3.8-flash-tts |
gemini-3.8-flash-lite-tts |
|---|---|---|
| Điểm mạnh chính | Giọng nói chân thực như trong phòng thu, sắc thái diễn xuất và khả năng hỗ trợ nhiều phương ngữ | Thông lượng cao, độ trễ thấp và tiết kiệm chi phí |
| Các trường hợp sử dụng phù hợp nhất | Sách nói, bản lồng tiếng trong phòng thu, cuộc trò chuyện phức tạp giữa nhiều người nói, thẻ bộc lộ cảm xúc thường xuyên, cách phát âm khó, phương ngữ vùng miền | Sản xuất số lượng lớn, tác nhân thoại theo thời gian thực, tính năng đọc to trên giao diện người dùng, giọng nói hằng ngày của một người nói |
| Ngôn ngữ được hỗ trợ | 132 ngôn ngữ | 103 ngôn ngữ |
Tạo lời nói từ văn bản
Bạn có thể tạo lời nói từ văn bản nhập vào bằng giọng nói của một người nói hoặc cuộc hội thoại của hai người nói, dưới dạng tệp WAV hoàn chỉnh (generateContent) hoặc dưới dạng luồng âm thanh PCM thô có độ trễ thấp (generateContentStream).
Tạo lời nói bằng một người nói
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Sau đây là cách tạo âm thanh có một người nói:
Trong
GenerationConfig, hãy đặtresponseModalitiesthànhAUDIOvà định cấu hìnhSpeechConfignhư sau:(Bắt buộc) Tên hoặc mã nhận dạng giọng nói. Đây có thể là một giọng nói tạo sẵn như
Kore, một mã nhận dạng giọng nói trong Thư viện giọng nói mở rộng hoặc một mã nhận dạngvoice_.../voicekey_...của giọng nói tuỳ chỉnh.(Không bắt buộc) Mã ngôn ngữ BCP-47. Nếu bạn bỏ qua, mô hình sẽ tự động phát hiện ngôn ngữ.
Tạo
TextPartbằng các thành phần sau:(Bắt buộc) Bản chép lời nguyên văn sẽ được đọc.
(Không bắt buộc)
SpeechMetadatacó nội dung mô tảstyle(ví dụ:"cheerful and friendly").
Gọi
generateContent. Theo mặc định, các yêu cầu một chiều sẽ trả về một tệp âm thanh WAV (audio/wav) hoàn chỉnh (PCM tuyến tính 16 bit, 24 kHz, đơn âm, có tiêu đề RIFF 44 byte tiêu chuẩn) trong các phần dữ liệu cùng dòng của phản hồi.
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
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// 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
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore"), "en-US"))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.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);
}
}
}
Tạo lời nói với nhiều người nói
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Bạn có thể tạo một cuộc trò chuyện tự nhiên giữa hai người nói trong một yêu cầu bằng cách chỉ định cho mỗi người nói một giọng nói riêng biệt và truyền từng dòng hội thoại dưới dạng TextPart riêng:
Tạo một
MultiSpeakerVoiceConfigliên kết hai tên người nói (ví dụ:"Joe"và"Jane") vớiSpeakerVoiceConfiggiọng nói của họ.Trong
GenerationConfig, hãy đặtresponseModalitiesthànhAUDIOvà truyềnMultiSpeakerVoiceConfig(vàlanguageCodekhông bắt buộc) vàoSpeechConfig.Cung cấp một mảng hoặc danh sách các đối tượng
TextPart, cụ thể là mộtTextPartcho mỗi lượt hội thoại. Trên mỗiTextPart, hãy đặtSpeechMetadatabằng các giá trị sau:- (Bắt buộc)
speakerkhớp với một trong các tên loa được xác định trongMultiSpeakerVoiceConfig. - (Không bắt buộc) Nội dung mô tả
style(ví dụ:"cheerful and friendly").
- (Bắt buộc)
Gọi
generateContent. Mô hình này tổng hợp toàn bộ cuộc trò chuyện và trả về một tệp âm thanh WAV (audio/wav) hoàn chỉnh.
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
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// 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
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
MultiSpeakerVoiceConfig multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
Arrays.asList(
new SpeakerVoiceConfig("Joe", new Voice("Puck")),
new SpeakerVoiceConfig("Jane", new Voice("Kore"))
)
);
SpeechConfig multiSpeechConfig = new SpeechConfig(multiSpeakerVoiceConfig, "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);
}
}
}
Hiển thị câu trả lời theo thời gian thực
|
Trước khi thử mẫu này, hãy hoàn tất phần Trước khi bắt đầu của hướng dẫn này để thiết lập dự án và ứng dụng của bạn. Trong phần đó, bạn cũng sẽ nhấp vào nút cho nhà cung cấp Gemini API mà bạn chọn để xem nội dung dành riêng cho nhà cung cấp trên trang này. |
Để giảm thời gian phát âm thanh đầu tiên (TTFA) và phát theo thời gian thực, bạn có thể phát trực tuyến phản hồi âm thanh khi phản hồi đó được tạo thay vì đợi toàn bộ đoạn âm thanh hoàn tất. Tính năng truyền trực tuyến hoạt động với cả cấu hình một loa và nhiều loa.
Để truyền trực tuyến lời nói, hãy gọi generateContentStream thay vì generateContent.
Không giống như các yêu cầu đơn lẻ (trả về tệp WAV), các yêu cầu truyền trực tuyến trả về các đoạn PCM không có tiêu đề, thô, 16 bit, có dấu, little-endian (audio/l16, 24 kHz, đơn âm) để bạn có thể nối trực tiếp từng đoạn vào vùng đệm đầu ra âm thanh.
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
Đối với Kotlin, các phương thức trong SDK này là hàm tạm ngưng và cần được gọi từ phạm vi Coroutine.
// 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
Đối với Java, các phương thức truyền trực tuyến trong SDK này sẽ trả về một loạiPublisher từ thư viện Reactive Streams.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore")))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.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);
}
}
Kiểm soát lời nói đầu ra bằng siêu dữ liệu và thẻ cùng dòng
Các mô hình Gemini 3.x TTS xử lý text bên trong mỗi TextPart
một cách nghiêm ngặt dưới dạng bản chép lời nguyên văn để đọc to. Đừng viết hướng dẫn tường thuật (chẳng hạn như "Say cheerfully:") bên trong chuỗi văn bản, nếu không, mô hình có thể đọc to những từ đó.
Bạn có thể điều chỉnh giọng hát bằng các kỹ thuật sau:
Thẻ giọng nói cùng dòng và style ở cấp độ lượt
Tách các chỉ dẫn về hiệu suất theo phạm vi giữa SpeechMetadata và các thẻ dấu ngoặc nhọn cùng dòng (<...>).
| Phạm vi | Vị trí đặt | Nội dung kiểm soát | Ví dụ |
|---|---|---|---|
|
Cấp độ rẽ (duy trì trong toàn bộ lượt rẽ) |
SpeechMetadata.style
|
Cảm xúc, tính cách, giọng điệu, ngữ điệu, cao độ và tốc độ nói tổng thể |
"cheerful and friendly","whispered, nervous","speaking rapidly","out of breath","sarcastic"
|
|
Thời điểm (được bản địa hoá theo một thời điểm cụ thể trong câu) |
Nội tuyến trong văn bản TextPart bằng <...>
|
Tiếng thở, tiếng thở dài, tiếng tạm dừng hoặc sự thay đổi tạm thời trong cách nói của con người không phải là lời nói |
"Wait... <short pause> did you hear that? <gasp> Someone's at the door."
|
Nhịp độ, khoảng nghỉ, cao độ và nhấn mạnh
Dấu câu và dấu ba chấm: Sử dụng dấu phẩy, dấu gạch ngang (
--) và dấu ba chấm (...) trong bản chép lời để tạo ra cách diễn đạt và sự ngập ngừng tự nhiên.Thẻ tạm dừng rõ ràng: Chèn
<short pause>hoặc<long pause>cùng dòng tại vị trí chính xác mà người nói nên tạm dừng:Hold on, let me think... <short pause> Alright, I've got it.Tốc độ nói và cao độ: Đặt
styletrongSpeechMetadatađể kiểm soát tốc độ, cao độ hoặc ngữ điệu tổng thể cho lượt nói (ví dụ:"speaking rapidly and excitedly","speaking slowly"hoặc"monotone and flat"). Nếu cảm xúc hoặc tốc độ thay đổi giữa chừng trong đoạn độc thoại, hãy chia kịch bản thành các lượt nóiTextPartriêng biệt, mỗi lượt cóstyleriêng.Nhấn mạnh từ: Viết hoa một số từ cụ thể trong bản chép lời để nhấn mạnh:
It was a VERY long day <sigh> ... nobody listens anymore.
Tiếng nói bộc phát và âm thanh không phải lời nói
Chèn âm thanh không phải lời nói của con người vào cùng dòng bằng cách sử dụng dấu ngoặc nhọn (<...>)
tại ranh giới từ chính xác nơi âm thanh sẽ phát ra. Sử dụng giọng nói của con người
thay vì hiệu ứng âm thanh không phải giọng nói. Dưới đây là các thẻ nên dùng:
<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> |
Từ đệm và giọng nói đè lên nhau
Trong cuộc hội thoại có nhiều người nói, bạn có thể gói gọn phản ứng ngắn gọn của người nghe trong các ký tự gạch đứng (|reaction|) bên trong bản chép lời của người đang nói. Người không nói sẽ xen vào một cách tự nhiên tại thời điểm đó mà không cần đợi đến lượt:
Phản hồi ngắn của người nghe:
- Lượt 1 (
speaker: "Joe"):"So the launch is Thursday |oh hmm| Are we actually ready?" - Lượt 2 (
speaker: "Jane"):"Ready enough |oh really?| The last blocker cleared this morning."
- Lượt 1 (
Lời nói chồng chéo: Bạn có thể sử dụng nhiều đoạn phân tách bằng dấu gạch đứng để mô phỏng lời nói đồng thời (hoạt động hiệu quả nhất với
gemini-3.8-flash-tts), chẳng hạn như:- Lượt 1 (
speaker: "Joe"):"Let's surprise him on three |ok| ready?" - Lượt 2 (
speaker: "Jane"):"one. two. three. |happy| happy |birthday| birthday!"
- Lượt 1 (
Các phương pháp hay nhất để đảm bảo tính nhất quán
Trước tiên, hãy thử nghiệm mà không có
style, sau đó thêm các điều chỉnh ngắn gọn chostyle: Hầu hết các yêu cầu đều nghe tự nhiên khi trườngstyletrống. Chỉ thêm một cụm từstylengắn (như"casual, friendly"hoặc"reflective and awe-inspired") khi một lượt cần điều chỉnh cách nói cụ thể và sử dụng lại cùng một chuỗi ngắn đó trong các lượt khi bạn muốn có một đường cơ sở nhất quán.Viết bản chép lời theo ngôn ngữ nói tự nhiên: Thêm các từ viết tắt trong văn nói và các từ đệm tự nhiên (như
"Oh, uh, yeah I think... hm, that's interesting") ngay trong văn bản chép lời.Tránh các khối
[Audio Profile]và siêu lệnh cũ: Các đoạn văn dài về tính cách, khối[Director's Notes]hoặc siêu lệnh như"maintain identical timbre"sẽ làm tăng độ lệch giọng nói. Thay vào đó, hãy chọn một giọng nói phù hợp trong Thư viện giọng nói mở rộng hoặc tạo giọng nói nhất quán cho nhân vật bằng tính năng Thiết kế giọng nói.Đừng cố gắng ghi đè các đặc điểm giọng nói không thể thay đổi trong
style: Tránh sử dụngSpeechMetadata.styleđể thay đổi tuổi, giới tính hoặc giọng điệu cố định của giọng nói. Thay vào đó, hãy chọn hoặc thiết kế một giọng nói có những đặc điểm đó.
Giọng nói được hỗ trợ
Các mô hình Gemini 3.x TTS hỗ trợ ba cách để chỉ định giọng nói:
Tất cả giọng nói đều đa ngôn ngữ, nghĩa là bạn có thể sử dụng cùng một giọng nói để tạo lời nói bằng bất kỳ ngôn ngữ nào được hỗ trợ trong khi vẫn giữ được danh tính người nói nhất quán. Ví dụ: nếu bạn đặt giọng nói thành giọng nói
Kore tạo sẵn và gửi câu lệnh bằng tiếng Tây Ban Nha, tiếng Hindi và tiếng Việt, thì tất cả câu trả lời
đều sử dụng giọng nói Kore bằng từng ngôn ngữ đó. Mặc dù 30 giọng nói cốt lõi được tạo sẵn là giọng nói đa ngôn ngữ cho mục đích chung, nhưng giọng nói trong Thư viện giọng nói mở rộng và giọng nói tuỳ chỉnh được liên kết với một ngôn ngữ chính hoặc giọng địa phương. Điều này có nghĩa là họ vẫn có thể nói các ngôn ngữ khác, nhưng giọng nói của họ nghe tự nhiên nhất bằng ngôn ngữ chính.
Giọng nói cốt lõi được tạo sẵn
Các mô hình TTS Gemini hỗ trợ 30 giọng nói cốt lõi được tạo sẵn (chẳng hạn như Kore, Puck, Zephyr, Charon và Fenrir), mỗi giọng nói có các đặc điểm giọng nói riêng biệt. Truyền tên giọng nói trong SpeechConfig (như trong ví dụ về một người nói và nhiều người nói ở phần trước của trang này).
Giọng nói đặt sẵn trong Thư viện giọng nói mở rộng
Ngoài 30 giọng nói tạo sẵn, Thư viện giọng nói mở rộng còn cung cấp hơn 2.000 giọng nói đặt trước được tuyển chọn, bao gồm nhiều ngôn ngữ, giọng vùng miền, nhóm tuổi, nhân vật và trường hợp sử dụng (chẳng hạn như sách nói, nhân viên hỗ trợ khách hàng và người đọc tin tức).
Sau đây là cách sử dụng giọng nói bất kỳ trong Thư viện giọng nói mở rộng trong ứng dụng của bạn:
Duyệt xem và nghe thử giọng nói bằng một trong các cách sau:
Sử dụng Google AI Studio hoặc Agent Studio để lấy giọng nói
id.Truy vấn phương thức
listcủa Voices API (ListVoicesbằngtype=prebuiltvà một truy vấnsearchkhông bắt buộc) để lấy giọng nóiid. Tìm hiểu thêm trong tài liệu về Gemini Developer API hoặc tài liệu về Agent Platform Gemini API (formerly Vertex AI).
Truyền chuỗi
idcủa giọng nói trong thư viện dưới dạng tên giọng nói trongSpeechConfig(tương tự như ví dụ về một người nói ở phần trước của trang này).
Giọng nói tuỳ chỉnh: Thiết kế giọng nói và nhân bản giọng nói
Các mô hình Gemini 3.x TTS cũng hỗ trợ giọng nói tuỳ chỉnh bằng một trong hai lựa chọn sau:
Thiết kế giọng nói (Bản dùng thử): Tạo giọng nói tuỳ chỉnh độc đáo từ nội dung mô tả bằng ngôn ngữ tự nhiên về độ tuổi, âm sắc, giọng điệu và tính cách của người nói (mà không cần bất kỳ âm thanh tham chiếu nào). Trả về mã giọng nói được lưu trữ (
voice_...).Nhân bản giọng nói (Bản dùng thử): Nhân bản giọng nói, giọng điệu và nhịp điệu của người nói từ một bản ghi âm tham chiếu và một bản ghi âm lời đồng ý. Trả về mã nhận dạng giọng nói được lưu trữ trong dự án (
voice_...) hoặc khoá nhân bản giọng nói không có trạng thái, do ứng dụng quản lý (voicekey_...).
Sử dụng giọng nói tuỳ chỉnh trong ứng dụng Firebase AI Logic
Việc tạo và quản lý giọng nói tuỳ chỉnh là một thao tác quản trị hoặc thao tác phía máy chủ, vì vậy, SDK ứng dụng Firebase AI Logic không trực tiếp hiển thị các điểm cuối quản lý Giọng nói (CreateVoice, ListVoices, DeleteVoice).
Thay vào đó, để sử dụng giọng nói tuỳ chỉnh, bạn cần làm như sau:
Tạo giọng nói tuỳ chỉnh một lần bằng một trong các lựa chọn sau:
Sử dụng Google AI Studio hoặc Agent Studio để lấy giá trị nhận dạng
voice_<id>hoặcvoicekey_<id>.Sử dụng Voices API để lấy giá trị nhận dạng
voice_<id>hoặcvoicekey_<id>. Tìm hiểu thêm trong tài liệu của nhà cung cấp Gemini API mà bạn chọn:Gemini Developer API: Tạo giọng nói
Agent Platform Gemini API (formerly Vertex AI): Thiết kế giọng nói và Nhân bản giọng nói
Truyền chuỗi
voice_<id>hoặcvoicekey_<id>dưới dạng tên giọng nói trongSpeechConfig(tương tự như nội dung trong ví dụ về một người nói ở phần trước của trang này).
Hãy lưu ý những yêu cầu sau khi sử dụng giọng nói tuỳ chỉnh:
Vị trí (Agent Platform Gemini API (formerly Vertex AI)): Giọng nói tuỳ chỉnh (
voice_...vàvoicekey_...) chỉ được hỗ trợ ở vị tríglobal(đây là vị trí mặc định khi sử dụng Firebase AI Logic).Yêu cầu một người nói:
MultiSpeakerVoiceConfigchỉ hỗ trợ giọng nói tạo sẵn chính. Để sử dụng giọng nói được thiết kế riêng hoặc giọng nói được sao chép trong một cuộc hội thoại có nhiều nhân vật, hãy tổng hợp lượt nói của từng nhân vật trong một yêu cầu riêng cho một người nói.Thời gian lưu giữ và hết hạn: Giọng nói tuỳ chỉnh được lưu trữ (
voice_...) sẽ hết hạn nếu không được sử dụng trong 1 năm (mỗi yêu cầu tổng hợp sẽ đặt lại bộ hẹn giờ lưu giữ 1 năm); khoá nhân bản giọng nói không có trạng thái (voicekey_...) sẽ hết hạn sau 7 ngày kể từ ngày tạo.
Ngôn ngữ được hỗ trợ
Các mô hình Gemini 3.x TTS tự động phát hiện ngôn ngữ từ văn bản đầu vào của bạn, kể cả khi câu lệnh chuyển đổi ngôn ngữ giữa các lượt trong một cuộc hội thoại có nhiều người nói.
- Gemini 3.8 Flash TTS (
gemini-3.8-flash-tts): Hỗ trợ 132 ngôn ngữ. - Gemini 3.8 Flash‑Lite TTS (
gemini-3.8-flash-lite-tts): Hỗ trợ 103 ngôn ngữ.
(Không bắt buộc) Đặt mã ngôn ngữ một cách rõ ràng
Nếu muốn ràng buộc rõ ràng việc tổng hợp lời nói với một ngôn ngữ cụ thể, bạn có thể truyền languageCode BCP-47 trong SpeechConfig:
Định dạng đầu ra âm thanh
Định dạng âm thanh mặc định được trả về trong InlineDataPart phụ thuộc vào việc bạn
gửi yêu cầu đơn nhất hay yêu cầu truyền trực tuyến:
| Phương thức yêu cầu | Loại MIME mặc định được trả về | Thông tin chi tiết về định dạng âm thanh |
|---|---|---|
|
Unary ( generateContent)
|
audio/wav
|
Tệp WAV hoàn chỉnh (PCM tuyến tính 16 bit, 24 kHz, đơn âm,
little-endian) có tiêu đề RIFF 44 byte tiêu chuẩn.
Có thể phát trực tiếp bằng trình phát âm thanh tiêu chuẩn của nền tảng (chẳng hạn như |
|
Phát trực tuyến ( generateContentStream)
|
audio/l16
|
Các đoạn PCM không có tiêu đề, thô, 16 bit, có dấu, little-endian
ở tần số 24 kHz, đơn âm.
Được thiết kế để xếp hàng đợi bộ đệm và phép nối có độ trễ thấp mà không cần tiêu đề tệp cho mỗi đoạn. |
Giới hạn và yêu cầu
Hãy lưu ý những hạn chế và yêu cầu sau đây khi sử dụng các mô hình Gemini 3.x TTS:
Chỉ nhập văn bản, chỉ xuất âm thanh: Các mô hình TTS chỉ chấp nhận dữ liệu đầu vào dạng văn bản (
TextPart) và yêu cầu đặtresponseModalitiesthànhAUDIO.Chỉ tổng hợp nguyên văn: Các mô hình đọc nguyên văn bản chép lời được cung cấp và không tạo câu trả lời bằng văn bản trò chuyện.
Giới hạn về mã thông báo: Đầu vào tối đa là 8.192 mã thông báo và đầu ra tối đa là 16.384 mã thông báo cho mỗi yêu cầu.
Giới hạn về số lượng người nói:
MultiSpeakerVoiceConfigyêu cầu 2 người nói và chỉ hỗ trợ giọng nói cốt lõi được tạo sẵn. MỗiTextParttrong yêu cầu nhiều người nói phải bao gồm mộtSpeechMetadata.speakerkhớp với một trong những người nói đã định cấu hình.Các tham số và phương thức không được hỗ trợ:
- SDK Firebase AI Logic chưa hỗ trợ việc đặt
responseFormattrongGenerationConfigđể ghi đè định dạng đầu ra âm thanh mặc định. - Việc đặt
systemInstruction,temperature,topP,topK,candidateCount,presencePenaltyhoặcfrequencyPenaltykhông được hỗ trợ và khiến các yêu cầu không thực hiện được kèm theo lỗi400 INVALID_ARGUMENT. - Không hỗ trợ việc gọi
countTokenscho các mô hình TTS (số lượng mã thông báo được trả về trongusageMetadatatrên phản hồi).
- SDK Firebase AI Logic chưa hỗ trợ việc đặt
Vị trí (Agent Platform Gemini API (formerly Vertex AI)): Giọng nói tuỳ chỉnh (
voice_...vàvoicekey_...) yêu cầu vị tríglobal(đây là vị trí mặc định khi sử dụng Firebase AI Logic).
Di chuyển từ gemini-3.1-flash-tts-preview
Cả gemini-3.8-flash-tts và gemini-3.8-flash-lite-tts đều sử dụng cùng một cấu trúc yêu cầu. Hãy xem bảng so sánh mô hình để chọn mô hình thay thế phù hợp nhất cho khối lượng công việc của bạn, đồng thời cập nhật mã như sau:
| Diện tích |
gemini-3.1-flash-tts-preview (Cũ)
|
gemini-3.8-flash-tts vàgemini-3.8-flash-lite-tts
|
|---|---|---|
| Phong cách và hướng dẫn trình bày |
Được nhúng trong văn bản câu lệnh. Ví dụ:"Say cheerfully: ...",[Audio Profile],[Director's Notes]
|
Đã vượt qua SpeechMetadata(style: "...") trên mỗi
TextPart
Giữ cho văn bản |
| Cuộc trò chuyện có nhiều người nói |
Chuỗi văn bản đơn có tiền tố "Speaker: ..." cùng dòng
|
Một TextPart cho mỗi lượt hội thoại, với
SpeechMetadata(speaker: "...", style: "...") trên mỗi
TextPart
|
| Thẻ giọng nói cùng dòng |
Dấu ngoặc vuông. Ví dụ:[sigh] hoặc [laughs]
|
Dấu ngoặc nhọn. Ví dụ:<sigh> hoặc
<laugh> hoặc
<short pause>
Viết trực tiếp các từ ngập ngừng như |
Định dạng âm thanh đơn nguyên mặc định
(generateContent)
|
PCM 16 bit thô không có tiêu đề (audio/pcm, 24 kHz, đơn âm)
|
Tệp WAV hoàn chỉnh (audio/wav, PCM 16 bit,
24 kHz, đơn âm, có tiêu đề RIFF 44 byte)
Truyền trực tuyến
( |
| Chỉ dẫn hệ thống, nhiệt độ, top-P, top-K | Bị bỏ qua |
Bị từ chối kèm theo lỗi 400 INVALID_ARGUMENT. Xoá các tham số này khỏi cấu hình mô hình của bạn.
|
Danh sách kiểm tra cho quá trình di chuyển
Nâng cấp lên phiên bản mới nhất của Firebase AI Logic SDK và cập nhật tên mô hình thành
gemini-3.8-flash-ttshoặcgemini-3.8-flash-lite-tts.Di chuyển hướng dẫn về phong cách vào
SpeechMetadata.style: Xoá tiền tố"Say cheerfully:", khối[Audio Profile],[Scene]và[Director's Notes]khỏi chuỗi câu lệnh để mô hình không đọc to các khối đó. Thay vào đó, hãy truyền một nội dung mô tả kiểu ngắn gọn trongSpeechMetadata.style.Tách kịch bản có nhiều người nói thành các lượt
TextPartriêng biệt: Thay thế các khối văn bản"Joe: ... \n Jane: ..."bằng một mảng/danh sách các đối tượngTextPart, trong đó mỗi lượt đặtSpeechMetadata.speaker.Chuyển đổi thẻ
[...]thành thẻ<...>: Thay thế thẻ âm thanh trong dấu ngoặc vuông (như[whispers],[sighs],[laughs]) bằng thẻ giọng hát trong dấu ngoặc nhọn (như<whispers>,<sigh>,<laugh>,<short pause>).Cập nhật chế độ phát âm thanh đơn phân: Vì
generateContenthiện trả về một tệp WAV hoàn chỉnh (có tiêu đề RIFF 44 byte) thay vì PCM thô không có tiêu đề, hãy xoá mọi mã thêm tiêu đề WAV vào phản hồi đơn phân theo cách thủ công (hoặc bỏ qua tiêu đề 44 byte nếu cung cấp mẫu PCM thô vào API vùng đệm cấp thấp nhưAudioTrackcủa Android hoặcAudioClipcủa Unity).Xoá các thông số cấu hình không được hỗ trợ: Xoá
temperature,topP,topK,candidateCount,presencePenalty,frequencyPenaltyvàsystemInstructionkhỏi cấu hìnhGenerativeModelcủa TTS.
Bạn có thể làm gì nữa?
-
Bắt đầu suy nghĩ về việc chuẩn bị phát hành công khai (xem danh sách kiểm tra phát hành công khai):
- Thực thi Firebase App Check càng sớm càng tốt để giúp bảo vệ Gemini API khỏi hành vi sai trái của các ứng dụng khách trái phép.
- Sử dụng Firebase Remote Config hoặc mẫu câu lệnh phía máy chủ để có thể thay đổi cấu hình theo yêu cầu cho tính năng AI (như tên mô hình) mà không cần phát hành phiên bản mới của ứng dụng.
Dùng thử các tính năng khác
- Xây dựng cuộc trò chuyện nhiều lượt (trò chuyện).
- Tạo văn bản do AI tạo từ câu lệnh chỉ có văn bản.
- Tạo kết quả có cấu trúc (như JSON) từ cả câu lệnh dạng văn bản và câu lệnh đa phương thức.
- Tạo và chỉnh sửa hình ảnh bằng cả câu lệnh dạng văn bản và đa phương thức.
- Truyền dữ liệu đầu vào và đầu ra (bao gồm cả âm thanh) bằng Gemini Live API.
-
Sử dụng các công cụ (như gọi hàm và Grounding bằng
Google Search hoặcGoogle Maps ) để kết nối mô hình Gemini với các phần khác của ứng dụng cũng như các hệ thống và thông tin bên ngoài.
Tìm hiểu cách kiểm soát việc tạo nội dung
- Tìm hiểu về thiết kế câu lệnh, bao gồm cả các phương pháp hay nhất, chiến lược và câu lệnh mẫu.
- Định cấu hình các tham số mô hình như số lượng mã thông báo đầu ra tối đa, xác suất lặp lại mã thông báo đầu ra, v.v.
- Sử dụng chế độ cài đặt an toàn để điều chỉnh khả năng nhận được câu trả lời có thể bị coi là gây hại.
Tìm hiểu thêm về các mô hình được hỗ trợ
Tìm hiểu về các mô hình có sẵn cho nhiều trường hợp sử dụng cũng như hạn mức và giá của các mô hình đó.Gửi ý kiến phản hồi về trải nghiệm của bạn với Firebase AI Logic