Tạo văn bản thành lời nói (TTS) bằng Gemini API


Bạn có thể yêu cầu mô hình Chuyển văn bản sang lời nói (TTS) Gemini tạo đầu ra âm thanh từ một câu lệnh văn bản. Khi sử dụng Firebase AI Logic, bạn có thể đưa ra yêu cầu này ngay từ ứng dụng của mình.

Bạn có thể kiểm soát quá trình tạo văn bản sang lời nói (TTS), tức là bạn cung cấp văn bản chính xác để tổng hợp thành lời nói. Ngoài ra, bạn có thể sử dụng ngôn ngữ tự nhiên trong câu lệnh để hướng dẫn về phong cách, giọng, tốc độ và tông giọng của đầu ra âm thanh. Bạn có thể coi TTS là trái ngược với tính năng phiên âm (chuyển lời nói sang văn bản).

Bạn có thể sử dụng tính năng này bằng bất kỳ mô hình Gemini -tts nào. Các mô hình này được tối ưu hoá để tạo ra lời nói chất lượng cao với độ trễ thấp.

Với tính năng này, bạn có thể làm những việc như:

  • Kể chuyện tương tác: Tạo sách nói hoặc trò chơi nhập vai sống động, trong đó mô hình chuyển đổi giọng nói cho các nhân vật khác nhau hoặc điều chỉnh giọng điệu (chẳng hạn như thì thầm trong hồi hộp hoặc cười khi nghe một câu chuyện cười) để phù hợp với câu chuyện.

  • Học ngôn ngữ: Tạo hướng dẫn phát âm có thể đọc văn bản với giọng địa phương cụ thể hoặc ở tốc độ chậm hơn để giúp người học luyện tập cách phát âm khó.

  • Trình đọc nội dung có nhận biết ngữ cảnh: Đọc to các bài viết tin tức, công thức nấu ăn hoặc bài đăng trên blog bằng một giọng điệu và tông giọng phù hợp với nội dung (chẳng hạn như tông giọng nghiêm túc cho tin tức nóng hổi hoặc tông giọng ấm áp, kiên nhẫn cho hướng dẫn nấu ăn từng bước).

Hướng dẫn này cho biết cách tạo lời nói từ dữ liệu đầu vào văn bản bằng một hoặc nhiều người nói và cách truyền trực tuyến phản hồi âm thanh.

Chuyển đến mã cho một loa Chuyển đến mã cho nhiều loa Chuyển đến mã cho các phản hồi được truyền 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à 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ụ những trường hợp sử dụng rất khác nhau.

  • Tạo văn bản sang lời nói (TTS) là một hoạt động tương tác một chiều theo yêu cầu-phản hồi (văn bản đầu vào, âm thanh đầu ra). Tính năng này được thiết kế riêng cho những trường hợp cần đọc chính xác văn bản được cung cấp với khả năng kiểm soát chi tiết về phong cách và âm thanh, chẳng hạn như lời dẫn trong podcast, sách nói hoặc đọc to các bài viết.

  • Live API thế hệ hỗ trợ tính năng phát trực tuyến hai chiều cho cuộc trò chuyện bằng giọng nói theo thời gian thực (giọng nói vào, giọng nói ra). Mô hình này vượt trội trong các ngữ cảnh trò chuyện linh động, nơi 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 để 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. Hướng dẫn này 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 chạy 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.

Để kiểm thử và cải tiến 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.1-flash-tts-preview

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 được cung cấp bằng cách sử dụng mô hình TTS Gemini.

Tạo lời nói bằng một người nói

Trước khi dùng 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 một 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ể định cấu hình mô hình để xuất âm thanh bằng một giọng nói duy nhất.

Trong GenerationConfig, hãy thêm nội dung sau:

Gọi generateContent bằng câu lệnh văn bản. Mô hình này trả về dữ liệu âm thanh PCM thô trong các phần 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.1-flash-tts-preview",
  generationConfig: config
)

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

// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
  let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
  let mimeType = part.mimeType  // for example: "audio/pcm"
  print("Received audio data with MIME type: \(mimeType)")

  // To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
  playRawPcm(data: data)
}

Kotlin

Đố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 qua 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.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
    .generativeModel(
        modelName = "gemini-3.1-flash-tts-preview",
        generationConfig = config
    )

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

// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
    val pcmData = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    val mimeType = part.mimeType   // for example: "audio/pcm"

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

Java

Đối với Java, các phương thức truyền phát trực tuyến trong SDK này sẽ trả về một loại Publisher 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.1-flash-tts-preview", config);

// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt.
String prompt = "Say cheerfully: Have a wonderful day!";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();

// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        Part part = result.getCandidates().get(0).getContent().getParts().get(0);
        if (part instanceof InlineDataPart) {
            byte[] pcmData = ((InlineDataPart) part).getInlineData();
            String mimeType = ((InlineDataPart) part).getMimeType();

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

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } },
    languageCode: "en-US"
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

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

// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();

// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
  const pcmBase64 = inlineDataParts[0].inlineData.data;
  // Decode base64 to ArrayBuffer
  const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

  // To play back a PCM buffer, you'll need to write your own `playAudio` function.
  playAudio(pcmBuffer);
}

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
  responseModalities: [ResponseModality.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);

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

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

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

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

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

Unity


using Firebase.AI;

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

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

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

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

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

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

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

Tạo lời nói có nhiều người nói

Trước khi dùng 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 một 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ể định cấu hình mô hình để sử dụng nhiều giọng nói cho nhiều người nói trong văn bản. Điều này hữu ích khi tạo âm thanh cho các đoạn hội thoại hoặc cuộc trò chuyện.

  1. Tạo một MultiSpeakerVoiceConfig ánh xạ tên người nói (bạn sẽ dùng trong câu lệnh) với tên giọng nói phản hồi cụ thể (ví dụ: Kore).

    Cấu hình nhiều loa hỗ trợ chính xác 2 loa.

  2. Trong GenerationConfig, hãy thêm nội dung sau:

    • Đặt responseModalities để bao gồm AUDIO.

    • Định cấu hình SpeechConfig bằng những thông tin sau:

  3. Trong câu lệnh, hãy cho biết người đang nói bằng cách sử dụng tên người nói làm tiền tố (ví dụ: Joe: Hello. Jane: Hi.).

Gọi generateContent bằng câu lệnh văn bản. Mô hình này trả về dữ liệu âm thanh PCM thô trong các phần phản hồi.

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
let multiSpeechConfig = SpeechConfig(
  multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
    speakerVoiceConfigs: [
      SpeakerVoiceConfig(speaker: "Joe", voiceName: "Puck"),
      SpeakerVoiceConfig(speaker: "Jane", voiceName: "Kore")
    ]
  ),
  languageCode: "en-US"
)

// Set `responseModalities` to include `audio`.
let config = GenerationConfig(
  responseModalities: [.audio],
  speechConfig: multiSpeechConfig
)

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

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

// Call `generateContent` to generate the speech output based on your text prompt.
let response = try await model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
  let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
  let mimeType = part.mimeType  // for example: "audio/pcm"
  print("Received audio data with MIME type: \(mimeType)")

  // To play back raw PCM audio bytes, you'll need to write your own `playRawPcm` function.
  playRawPcm(data: data)
}

Kotlin

Đố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 qua 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.1-flash-tts-preview",
        generationConfig = config
    )

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

// Call `generateContent` to generate the speech output based on your text prompt.
val response = model.generateContent(prompt)

// Extract the audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
    val pcmData = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    val mimeType = part.mimeType   // for example: "audio/pcm"

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

Java

Đối với Java, các phương thức truyền phát trực tuyến trong SDK này sẽ trả về một loại Publisher 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);

// Set `responseModalities` to include `AUDIO`.
GenerationConfig config = new GenerationConfig.Builder()
    .setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
    .setSpeechConfig(multiSpeechConfig)
    .build();

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

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt that includes the names of the speakers.
String prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();

// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        Part part = result.getCandidates().get(0).getContent().getParts().get(0);
        if (part instanceof InlineDataPart) {
            byte[] pcmData = ((InlineDataPart) part).getInlineData();  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
            String mimeType = ((InlineDataPart) part).getMimeType();   // for example: "audio/pcm"

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

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    multiSpeakerVoiceConfig: {
      speakerVoiceConfigs: [
        { speaker: "Joe", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Puck" } } },
        { speaker: "Jane", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
      ]
    },
    languageCode: "en-US"
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

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

// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();

// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
  const pcmBase64 = inlineDataParts[0].inlineData.data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
  const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

  // To play back a PCM buffer, you'll need to write your own `playAudio` function.
  playAudio(pcmBuffer);
}

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
final multiSpeechConfig = SpeechConfig.multiSpeaker(
  multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
    speakerVoiceConfigs: [
      SpeakerVoiceConfig(speaker: 'Joe', voiceName: 'Puck'),
      SpeakerVoiceConfig(speaker: 'Jane', voiceName: 'Kore'),
    ],
  ),
  languageCode: 'en-US',
);

// Set `responseModalities` to include `audio`.
final config = GenerationConfig(
  responseModalities: [ResponseModality.audio],
  speechConfig: multiSpeechConfig,
);

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

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

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

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

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

Unity


using Firebase.AI;

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

var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);

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

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

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

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

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

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

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

Hiện câu trả lời theo thời gian thực

Trước khi dùng 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 một 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 được tốc độ tương tác nhanh hơn và độ trễ thấp hơn bằng cách truyền trực tuyến phản hồi âm thanh khi phản hồi đó được tạo, thay vì chờ toàn bộ tệp âm thanh hoàn tất.

Tính năng phát trực tuyến lời nói được tạo được hỗ trợ cho cả cấu hình một người nóinhiều người nói. Chỉ được hỗ trợ khi dùng các mô hình Gemini 3.x TTS.

Để truyền trực tuyến phản hồi bằng lời nói, hãy gọi generateContentStream thay vì generateContent và xử lý các đoạn khi chúng đến. Các ví dụ sau đây cho thấy cách truyền trực tuyến một phản hồi của một người nó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")
)

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

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

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
let responseStream = try model.generateContentStream(prompt)

// Extract the audio data and handle it for downstream use. For example:
for try await chunk in responseStream {
  for part in chunk.inlineDataParts {
    let data = part.data          // Raw PCM audio bytes (24kHz, 1 channel, 16-bit)
    let mimeType = part.mimeType  // for example: "audio/pcm"

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

Kotlin

Đố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 qua 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.1-flash-tts-preview",
        generationConfig = config
    )

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

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
// Extract the audio data and handle it for downstream use.
model.generateContentStream(prompt).collect { chunk ->
    val part = chunk.candidates.firstOrNull()?.content?.parts?.firstOrNull()
    if (part is InlineDataPart) {
        val pcmChunk = part.inlineData  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
        val mimeType = part.mimeType    // for example: "audio/pcm"

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

Java

Đối với Java, các phương thức truyền phát trực tuyến trong SDK này sẽ trả về một loại Publisher 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.1-flash-tts-preview", config);

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide a text prompt.
String prompt = "Tell me a story about a brave knight.";
Content content = new Content.Builder().addText(prompt).build();

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
Publisher<GenerateContentResponse> streamingResponse =
    model.generateContentStream(content);

// Extract the audio data and handle it for downstream use.
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
  @Override
  public void onSubscribe(Subscription s) {
      s.request(Long.MAX_VALUE);
  }

  @Override
  public void onNext(GenerateContentResponse chunk) {
      Part part = chunk.getCandidates().get(0).getContent().getParts().get(0);
      if (part instanceof InlineDataPart) {
          byte[] pcmChunk = ((InlineDataPart) part).getInlineData();  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
          String mimeType = ((InlineDataPart) part).getMimeType();    // for example: "audio/pcm"

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

  @Override
  public void onComplete() {
      // Audio stream complete.
  }

  @Override
  public void onError(Throwable t) {
      t.printStackTrace();
  }
});

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";

// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
  responseModalities: [ResponseModality.AUDIO],
  speechConfig: {
    voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } }
  }
};

// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
  model: "gemini-3.1-flash-tts-preview",
  generationConfig
});

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

// Call `generateContentStream` to generate the speech output stream based on your text prompt.
const result = await model.generateContentStream(prompt);

// Extract the audio data and handle it for downstream use. For example:
const playbackQueue = [];
for await (const chunk of result.stream) {
  const inlineDataParts = chunk.inlineDataParts();
  if (inlineDataParts?.[0]) {
    const pcmBase64 = inlineDataParts[0].inlineData.data;  // Raw PCM bytes (24kHz, 1 channel, 16-bit)
    const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;

    // Append the audio chunk to your audio queue/buffer for playback.
    playbackQueue.push(pcmBuffer);
  }
}

// To play back an array of PCM buffers in sequence, you'll need to write your own `processPlaybackQueue` function.
processPlaybackQueue(playbackQueue);

Dart


import 'package:firebase_ai/firebase_ai.dart';

// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
  responseModalities: [ResponseModality.audio],
  speechConfig: SpeechConfig(voiceName: 'Kore'),
);

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

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

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

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

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

Unity


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

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

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

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

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

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

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

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

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



Kiểm soát lời nói đầu ra bằng câu lệnh

Bạn có thể tác động đến giọng điệu, tốc độ và phong cách của lời nói được tạo bằng các kỹ thuật gợi ý cụ thể.

Các tiểu mục sau đây về cấu trúc câu lệnhthẻ âm thanh mô tả hướng dẫn cấp cao. Để biết hướng dẫn chi tiết, hãy tham khảo hướng dẫn tạo câu lệnh này.

Cấu trúc câu lệnh

Để có kết quả tốt nhất, hãy tạo câu lệnh có các thành phần sau:

  • Audio Profile: Mô tả tính cách, bản sắc cốt lõi và nguyên mẫu của người nói (ví dụ: A warm, professional narrator).

  • Scene: Mô tả môi trường và bầu không khí cảm xúc (ví dụ: In a quiet library hoặc Amidst a noisy crowd).

  • Director's Notes: Mô tả cảm xúc, nhịp độ, phong cách và giọng điệu (ví dụ: Speak slowly and with mystery).

  • Sample Context: Đưa ra một điểm xuất phát cho mô hình (ví dụ: The speaker is greeting a close friend).

  • Bản chép lời: Văn bản thực tế sẽ được đọc. Để có hiệu suất tốt nhất, hãy đảm bảo giọng điệu và ngữ cảnh của văn bản phù hợp với hồ sơ giọng nói và ghi chú của đạo diễn.

Câu lệnh mẫu:

[Audio Profile: A young, energetic voice]
[Scene: A lively sports broadcast]
[Director's Notes: Speak fast, with high energy and excitement]
[Sample Context: The game just ended with a last-second touchdown]
Welcome back fans! What an incredible game we're witnessing today!

Thẻ âm thanh

Bạn có thể chèn trực tiếp các thẻ định dạng vào câu lệnh văn bản để hướng dẫn hiệu suất của mô hình.

Thẻ âm thanh chỉ được hỗ trợ khi sử dụng các mô hình Gemini 3.x TTS.

Sau đây là một số thẻ thường dùng:

  • [whispers]: Để nói thì thầm
  • [laughs]: Để thêm tiếng cười
  • [giggles]: Cách thêm tiếng cười khúc khích
  • [sighs]: Để thêm tiếng thở dài
  • [gasp]: Để thêm tiếng thở dốc
  • [shouting]: Nói to
  • [excited]: Để nói một cách hào hứng
  • [serious]: Nói một cách nghiêm túc
  • [sighs whispers]: Cảm xúc kết hợp (bạn có thể kết hợp các thẻ)

Khi sử dụng thẻ âm thanh, hãy lưu ý những điều sau:

  • Không có danh sách đầy đủ: Không có danh sách cố định về các thẻ được hỗ trợ. Bạn có thể thử nghiệm nhiều cảm xúc và biểu cảm (chẳng hạn như [bored], [sarcastically] hoặc thậm chí là [like dracula]) để xem kết quả thay đổi như thế nào.

  • Câu lệnh văn bản không phải tiếng Anh: Nếu câu lệnh văn bản của bạn không phải tiếng Anh, bạn vẫn nên sử dụng thẻ âm thanh bằng tiếng Anh để có kết quả tốt nhất.

Câu lệnh mẫu:

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



Giới hạn và yêu cầu

Khi sử dụng tính năng tạo lời nói, hãy lưu ý những hạn chế và yêu cầu sau:

  • Cấu hình nhiều loa hỗ trợ chính xác 2 loa.

  • Các tính năng sau đây chỉ được hỗ trợ khi bạn sử dụng các mô hình Gemini 3.x TTS: phát trực tuyến, thẻ âm thanh và các ngôn ngữ khác được tự động phát hiện.

Các ràng buộc đối với gemini-3.1-flash-tts-preview

  • Giọng nói không nhất quán: Đầu ra của mô hình có thể không phải lúc nào cũng hoàn toàn khớp với người nói đã chọn nếu giọng điệu và ngữ cảnh của câu lệnh không phù hợp với hồ sơ của người nói (ví dụ: giọng nam trầm cố gắng nói như một cô gái trẻ). Đảm bảo ngữ cảnh của câu lệnh phù hợp với giọng nói.
  • Đầu ra dài hơn: Chất lượng và tính nhất quán của lời nói có thể giảm sút đối với âm thanh dài hơn vài phút. Bạn nên chia các câu lệnh dài thành những phần nhỏ hơn.
  • Đôi khi trả về mã thông báo văn bản: Đôi khi, mô hình trả về mã thông báo văn bản thay vì mã thông báo âm thanh, khiến yêu cầu không thành công và gặp lỗi 500. Vì điều này xảy ra ngẫu nhiên trong một tỷ lệ nhỏ các yêu cầu, nên bạn cần triển khai logic thử lại trong ứng dụng của mình.
  • Phân loại sai: Câu lệnh mơ hồ có thể không vượt qua được bộ phân loại tổng hợp lời nói, dẫn đến yêu cầu bị từ chối (PROHIBITED_CONTENT) hoặc khiến mô hình đọc to hướng dẫn về phong cách của bạn. Để tránh trường hợp này, hãy sử dụng một câu lệnh có cấu trúc với phần mở đầu rõ ràng (chẳng hạn như Audio ProfileDirector's Notes) ở đầu câu lệnh.



Ngôn ngữ và giọng nói được hỗ trợ

Các mô hình TTS Gemini nhận đầu vào văn bản và tạo đầu ra âm thanh, vì vậy, phản hồi chính là lời nói được tổng hợp. Các mục con sau đây liệt kê những giọng nói và ngôn ngữ được hỗ trợ mà các mô hình TTS Gemini có thể "nói" (hoặc phản hồi).

Các giọng nói này hỗ trợ nhiều ngôn ngữ, tức là bạn có thể 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ợ. Ví dụ: bạn có thể đặt giọng nói thành Kore và gửi một bộ câu lệnh văn bản bằng tiếng Tây Ban Nha, tiếng Hindi và tiếng Việt. Các câu trả lời sẽ đều bằng giọng của Kore, nhưng bằng mỗi ngôn ngữ trong số đó.

Tên giọng nói

Các mô hình Gemini TTS hỗ trợ 30 giọng nói HD được tổng hợp khác nhau, mỗi giọng nói có đặc điểm riêng biệt. Bạn có thể xem danh sách các lựa chọn về giọng nói phản hồi và nghe bản minh hoạ của từng giọng nói bằng cách mở rộng phần bên dưới.

Ngôn ngữ

Các mô hình TTS Gemini có thể tự động phát hiện các ngôn ngữ sau đây trong câu lệnh văn bản của bạn. Lời nói được tạo sẽ bằng ngôn ngữ đó.

Xin lưu ý rằng bạn có thể thiết lập mã ngôn ngữ một cách rõ ràng trong cấu hình lời nói (không bắt buộc).

Các ngôn ngữ được tất cả mô hình tạo âm thanh hỗ trợ
Ngôn ngữ Mã BCP-47 Ngôn ngữ Mã BCP-47
Tiếng Ả Rập (Ai Cập) ar-EG Tiếng Đức (Đức) de-DE
Tiếng Anh (Mỹ) en-US Tiếng Tây Ban Nha (Mỹ) es-US
Tiếng Pháp (Pháp) fr-FR Tiếng Hindi (Ấn Độ) hi-IN
Tiếng Indonesia (Indonesia) id-ID Tiếng Ý (Ý) it-IT
Tiếng Nhật (Nhật Bản) ja-JP Tiếng Hàn (Hàn Quốc) ko-KR
Tiếng Bồ Đào Nha (Brazil) pt-BR Tiếng Nga (Nga) ru-RU
Tiếng Hà Lan (Hà Lan) nl-NL Tiếng Ba Lan (Ba Lan) pl-PL
Tiếng Thái (Thái Lan) th-TH Tiếng Thổ Nhĩ Kỳ (Thổ Nhĩ Kỳ) tr-TR
Tiếng Việt (Việt Nam) vi-VN Tiếng Rumani (Rumani) ro-RO
Tiếng Ukraina (Ukraina) uk-UA Tiếng Bengali (Bangladesh) bn-BD
Tiếng Anh (Ấn Độ) Gói en-IN và hi-IN Tiếng Marathi (Ấn Độ) mr-IN
Tiếng Tamil (Ấn Độ) ta-IN Tiếng Telugu (Ấn Độ) te-IN
Các ngôn ngữ khác được hỗ trợ bởi mô hình 3.x tạo âm thanh
Ngôn ngữ Mã BCP-47 Ngôn ngữ Mã BCP-47
Tiếng Hà Lan ở Nam Phi af Tiếng Philippines fil
Tiếng Albania sq Tiếng Phần Lan fi
Tiếng Amhara sáng Tiếng Galicia gl
Tiếng Armenia hy Tiếng Gruzia ka
Tiếng Azerbaijan az Tiếng Hy Lạp el
Tiếng Basque eu Tiếng Gujarat gu
Tiếng Belarus be Tiếng Creole ở Haiti ht
Tiếng Bungary bg Tiếng Do Thái he
Tiếng Miến Điện của tôi Tiếng Hungary hu
Tiếng Catalan ca Tiếng Iceland
Tiếng Cebuano ceb Tiếng Java jv
Tiếng Trung, tiếng Quan thoại cmn Tiếng Kannada kn
Tiếng Croatia giờ Tiếng Konkani kok
Tiếng Séc cs Tiếng Lào lo
Tiếng Đan Mạch da Tiếng Latinh la
Tiếng Estonia et Tiếng Latvia lv
Tiếng Lithuania lt Tiếng Luxembourg lb
Tiếng Macedonia mk Tiếng Maithili mai
Tiếng Malagasy mg Tiếng Malay ms
Tiếng Malayalam ml Tiếng Mông Cổ mn
Tiếng Nepal ne Tiếng Na Uy, Bokmål nb
Tiếng Na Uy, Nynorsk nn Tiếng Odia hoặc
Tiếng Pashto ps Tiếng Ba Tư fa
Tiếng Punjab pa Tiếng Serbia sr
Tiếng Sindh sd Tiếng Sinhala si
Tiếng Slovak sk Tiếng Slovenia sl
Tiếng Swahili sw Tiếng Thuỵ Điển sv
Tiếng Urdu ur

(Không bắt buộc) Đặt mã ngôn ngữ một cách rõ ràng

Nếu bạn không chỉ định mã ngôn ngữ trong cấu hình lời nói, thì mô hình sẽ tự động phát hiện ngôn ngữ trong câu lệnh văn bản của bạn.

Tuy nhiên, bạn có thể đặt ngôn ngữ một cách rõ ràng (không bắt buộc) bằng cách sử dụng tham số languageCode trong cấu hình lời nói. Để làm việc này, bạn phải sử dụng một trong các mã ngôn ngữ BCP-47 được hỗ trợ sau đây:

  • Tiếng Ả Rập: ar-XA
  • Tiếng Bengali: bn-IN
  • Tiếng Trung (Quan thoại): cmn-CN
  • Tiếng Hà Lan: nl-NL
  • Tiếng Anh: en-US, en-GB, en-AU, en-IN
  • Tiếng Pháp: fr-FR, fr-CA
  • Tiếng Đức: de-DE
  • Tiếng Gujarati: gu-IN
  • Tiếng Hindi: hi-IN
  • Tiếng Indonesia: id-ID
  • Tiếng Ý: it-IT
  • Tiếng Nhật: ja-JP
  • Tiếng Kannada: kn-IN
  • Tiếng Hàn: ko-KR
  • Tiếng Malayalam: ml-IN
  • Tiếng Marathi: mr-IN
  • Tiếng Ba Lan: pl-PL
  • Tiếng Bồ Đào Nha: pt-BR
  • Tiếng Nga: ru-RU
  • Tiếng Tây Ban Nha: es-US, es-ES
  • Tiếng Tamil: ta-IN
  • Tiếng Telugu: te-IN
  • Tiếng Thái: th-TH
  • Tiếng Thổ Nhĩ Kỳ: tr-TR
  • Tiếng Việt: vi-VN



Bạn có thể làm gì khác?

Thử các chức năng khác

Tìm hiểu cách kiểm soát hoạt động tạo nội dung

Bạn cũng có thể thử nghiệm với các câu lệnh và cấu hình mô hình, thậm chí nhận được một đoạn mã được tạo bằng Google AI Studio.

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ụnghạn mức cũng như 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