Tạo lời nói (chuyển văn bản sang lời nói)

Gemini API có thể chuyển đổi văn bản đầu vào thành âm thanh của một hoặc nhiều người nói bằng cách sử dụng các chức năng tạo văn bản thành lời nói (TTS) gốc. 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 có thể dùng ngôn ngữ tự nhiên để cấu trúc các lượt tương tác và hướng dẫn phong cách, giọng, tốc độgiọng điệu của âm thanh.

Khả năng TTS khác với khả năng tạo lời nói được cung cấp thông qua Live API. API này được thiết kế cho âm thanh tương tác, không có cấu trúc, cũng như đầu vào và đầu ra đa phương thức. Mặc dù Live API vượt trội trong các bối cảnh trò chuyện linh hoạt, nhưng TTS thông qua Gemini API được điều chỉnh cho phù hợp với những trường hợp yêu cầu đọc chính xác văn bản với khả năng kiểm soát chi tiết về phong cách và âm thanh, chẳng hạn như tạo podcast hoặc sách nói.

Hướng dẫn này trình bày cách tạo âm thanh một người nói và nhiều người nói từ văn bản.

Trước khi bắt đầu

Đảm bảo bạn sử dụng một biến thể mô hình Gemini 2.5 có các chức năng chuyển văn bản sang lời nói (TTS) gốc, như được liệt kê trong phần Các mô hình được hỗ trợ. Để có kết quả tối ưu, hãy cân nhắc xem mô hình nào phù hợp nhất với trường hợp sử dụng cụ thể của bạn.

Bạn nên kiểm thử các mô hình TTS Gemini 2.5 trong AI Studio trước khi bắt đầu xây dựng.

Tính năng chuyển văn bản sang lời nói cho một người nói

Để chuyển văn bản thành âm thanh của một người nói, hãy đặt phương thức phản hồi thành "audio" và truyền một đối tượng SpeechConfigVoiceConfig được đặt. Bạn cần chọn tên giọng nói trong số những giọng nói đầu ra được tạo sẵn.

Ví dụ này lưu âm thanh đầu ra từ mô hình vào một tệp sóng:

Python

from google import genai
from google.genai import types
import wave

# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
   with wave.open(filename, "wb") as wf:
      wf.setnchannels(channels)
      wf.setsampwidth(sample_width)
      wf.setframerate(rate)
      wf.writeframes(pcm)

client = genai.Client()

response = client.models.generate_content(
   model="gemini-2.5-flash-preview-tts",
   contents="Say cheerfully: Have a wonderful day!",
   config=types.GenerateContentConfig(
      response_modalities=["AUDIO"],
      speech_config=types.SpeechConfig(
         voice_config=types.VoiceConfig(
            prebuilt_voice_config=types.PrebuiltVoiceConfig(
               voice_name='Kore',
            )
         )
      ),
   )
)

data = response.candidates[0].content.parts[0].inline_data.data

file_name='out.wav'
wave_file(file_name, data) # Saves the file to current directory

JavaScript

import {GoogleGenAI} from '@google/genai';
import wav from 'wav';

async function saveWaveFile(
   filename,
   pcmData,
   channels = 1,
   rate = 24000,
   sampleWidth = 2,
) {
   return new Promise((resolve, reject) => {
      const writer = new wav.FileWriter(filename, {
            channels,
            sampleRate: rate,
            bitDepth: sampleWidth * 8,
      });

      writer.on('finish', resolve);
      writer.on('error', reject);

      writer.write(pcmData);
      writer.end();
   });
}

async function main() {
   const ai = new GoogleGenAI({});

   const response = await ai.models.generateContent({
      model: "gemini-2.5-flash-preview-tts",
      contents: [{ parts: [{ text: 'Say cheerfully: Have a wonderful day!' }] }],
      config: {
            responseModalities: ['AUDIO'],
            speechConfig: {
               voiceConfig: {
                  prebuiltVoiceConfig: { voiceName: 'Kore' },
               },
            },
      },
   });

   const data = response.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
   const audioBuffer = Buffer.from(data, 'base64');

   const fileName = 'out.wav';
   await saveWaveFile(fileName, audioBuffer);
}
await main();

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
        "contents": [{
          "parts":[{
            "text": "Say cheerfully: Have a wonderful day!"
          }]
        }],
        "generationConfig": {
          "responseModalities": ["AUDIO"],
          "speechConfig": {
            "voiceConfig": {
              "prebuiltVoiceConfig": {
                "voiceName": "Kore"
              }
            }
          }
        },
        "model": "gemini-2.5-flash-preview-tts",
    }' | jq -r '.candidates[0].content.parts[0].inlineData.data' | \
          base64 --decode >out.pcm
# You may need to install ffmpeg.
ffmpeg -f s16le -ar 24000 -ac 1 -i out.pcm out.wav

Chuyển văn bản sang lời nói có nhiều người nói

Đối với âm thanh nhiều loa, bạn sẽ cần một đối tượng MultiSpeakerVoiceConfig có mỗi loa (tối đa 2) được định cấu hình dưới dạng SpeakerVoiceConfig. Bạn sẽ cần xác định từng speaker bằng các tên giống nhau được dùng trong lệnh:

Python

from google import genai
from google.genai import types
import wave

# Set up the wave file to save the output:
def wave_file(filename, pcm, channels=1, rate=24000, sample_width=2):
   with wave.open(filename, "wb") as wf:
      wf.setnchannels(channels)
      wf.setsampwidth(sample_width)
      wf.setframerate(rate)
      wf.writeframes(pcm)

client = genai.Client()

prompt = """TTS the following conversation between Joe and Jane:
         Joe: How's it going today Jane?
         Jane: Not too bad, how about you?"""

response = client.models.generate_content(
   model="gemini-2.5-flash-preview-tts",
   contents=prompt,
   config=types.GenerateContentConfig(
      response_modalities=["AUDIO"],
      speech_config=types.SpeechConfig(
         multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
            speaker_voice_configs=[
               types.SpeakerVoiceConfig(
                  speaker='Joe',
                  voice_config=types.VoiceConfig(
                     prebuilt_voice_config=types.PrebuiltVoiceConfig(
                        voice_name='Kore',
                     )
                  )
               ),
               types.SpeakerVoiceConfig(
                  speaker='Jane',
                  voice_config=types.VoiceConfig(
                     prebuilt_voice_config=types.PrebuiltVoiceConfig(
                        voice_name='Puck',
                     )
                  )
               ),
            ]
         )
      )
   )
)

data = response.candidates[0].content.parts[0].inline_data.data

file_name='out.wav'
wave_file(file_name, data) # Saves the file to current directory

JavaScript

import {GoogleGenAI} from '@google/genai';
import wav from 'wav';

async function saveWaveFile(
   filename,
   pcmData,
   channels = 1,
   rate = 24000,
   sampleWidth = 2,
) {
   return new Promise((resolve, reject) => {
      const writer = new wav.FileWriter(filename, {
            channels,
            sampleRate: rate,
            bitDepth: sampleWidth * 8,
      });

      writer.on('finish', resolve);
      writer.on('error', reject);

      writer.write(pcmData);
      writer.end();
   });
}

async function main() {
   const ai = new GoogleGenAI({});

   const prompt = `TTS the following conversation between Joe and Jane:
         Joe: How's it going today Jane?
         Jane: Not too bad, how about you?`;

   const response = await ai.models.generateContent({
      model: "gemini-2.5-flash-preview-tts",
      contents: [{ parts: [{ text: prompt }] }],
      config: {
            responseModalities: ['AUDIO'],
            speechConfig: {
               multiSpeakerVoiceConfig: {
                  speakerVoiceConfigs: [
                        {
                           speaker: 'Joe',
                           voiceConfig: {
                              prebuiltVoiceConfig: { voiceName: 'Kore' }
                           }
                        },
                        {
                           speaker: 'Jane',
                           voiceConfig: {
                              prebuiltVoiceConfig: { voiceName: 'Puck' }
                           }
                        }
                  ]
               }
            }
      }
   });

   const data = response.candidates?.[0]?.content?.parts?.[0]?.inlineData?.data;
   const audioBuffer = Buffer.from(data, 'base64');

   const fileName = 'out.wav';
   await saveWaveFile(fileName, audioBuffer);
}

await main();

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{
  "contents": [{
    "parts":[{
      "text": "TTS the following conversation between Joe and Jane:
                Joe: Hows it going today Jane?
                Jane: Not too bad, how about you?"
    }]
  }],
  "generationConfig": {
    "responseModalities": ["AUDIO"],
    "speechConfig": {
      "multiSpeakerVoiceConfig": {
        "speakerVoiceConfigs": [{
            "speaker": "Joe",
            "voiceConfig": {
              "prebuiltVoiceConfig": {
                "voiceName": "Kore"
              }
            }
          }, {
            "speaker": "Jane",
            "voiceConfig": {
              "prebuiltVoiceConfig": {
                "voiceName": "Puck"
              }
            }
          }]
      }
    }
  },
  "model": "gemini-2.5-flash-preview-tts",
}' | jq -r '.candidates[0].content.parts[0].inlineData.data' | \
    base64 --decode > out.pcm
# You may need to install ffmpeg.
ffmpeg -f s16le -ar 24000 -ac 1 -i out.pcm out.wav

Kiểm soát phong cách nói bằng câu lệnh

Bạn có thể kiểm soát phong cách, giọng điệu, giọng nói và tốc độ bằng cách sử dụng câu lệnh bằng ngôn ngữ tự nhiên cho cả TTS một người nói và nhiều người nói. Ví dụ: trong câu lệnh có một người nói, bạn có thể nói:

Say in an spooky whisper:
"By the pricking of my thumbs...
Something wicked this way comes"

Trong câu lệnh có nhiều người nói, hãy cung cấp cho mô hình tên của từng người nói và bản chép lời tương ứng. Bạn cũng có thể hướng dẫn riêng cho từng người nói:

Make Speaker1 sound tired and bored, and Speaker2 sound excited and happy:

Speaker1: So... what's on the agenda today?
Speaker2: You're never going to guess!

Hãy thử dùng một lựa chọn về giọng nói tương ứng với phong cách hoặc cảm xúc mà bạn muốn truyền tải để nhấn mạnh hơn nữa. Ví dụ: trong câu lệnh trước, hơi thở của Enceladus có thể nhấn mạnh trạng thái "mệt mỏi" và "buồn chán", trong khi giọng điệu lạc quan của Puck có thể bổ sung cho trạng thái "phấn khích" và "vui vẻ".

Tạo câu lệnh để chuyển đổi thành âm thanh

Các mô hình TTS chỉ xuất âm thanh, nhưng bạn có thể sử dụng các mô hình khác để tạo bản chép lời trước, sau đó chuyển bản chép lời đó đến mô hình TTS để đọc to.

Python

from google import genai
from google.genai import types

client = genai.Client()

transcript = client.models.generate_content(
   model="gemini-2.0-flash",
   contents="""Generate a short transcript around 100 words that reads
            like it was clipped from a podcast by excited herpetologists.
            The hosts names are Dr. Anya and Liam.""").text

response = client.models.generate_content(
   model="gemini-2.5-flash-preview-tts",
   contents=transcript,
   config=types.GenerateContentConfig(
      response_modalities=["AUDIO"],
      speech_config=types.SpeechConfig(
         multi_speaker_voice_config=types.MultiSpeakerVoiceConfig(
            speaker_voice_configs=[
               types.SpeakerVoiceConfig(
                  speaker='Dr. Anya',
                  voice_config=types.VoiceConfig(
                     prebuilt_voice_config=types.PrebuiltVoiceConfig(
                        voice_name='Kore',
                     )
                  )
               ),
               types.SpeakerVoiceConfig(
                  speaker='Liam',
                  voice_config=types.VoiceConfig(
                     prebuilt_voice_config=types.PrebuiltVoiceConfig(
                        voice_name='Puck',
                     )
                  )
               ),
            ]
         )
      )
   )
)

# ...Code to stream or save the output

JavaScript

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({});

async function main() {

const transcript = await ai.models.generateContent({
   model: "gemini-2.0-flash",
   contents: "Generate a short transcript around 100 words that reads like it was clipped from a podcast by excited herpetologists. The hosts names are Dr. Anya and Liam.",
   })

const response = await ai.models.generateContent({
   model: "gemini-2.5-flash-preview-tts",
   contents: transcript,
   config: {
      responseModalities: ['AUDIO'],
      speechConfig: {
         multiSpeakerVoiceConfig: {
            speakerVoiceConfigs: [
                   {
                     speaker: "Dr. Anya",
                     voiceConfig: {
                        prebuiltVoiceConfig: {voiceName: "Kore"},
                     }
                  },
                  {
                     speaker: "Liam",
                     voiceConfig: {
                        prebuiltVoiceConfig: {voiceName: "Puck"},
                    }
                  }
                ]
              }
            }
      }
  });
}
// ..JavaScript code for exporting .wav file for output audio

await main();

Lựa chọn giọng nói

Các mô hình TTS hỗ trợ 30 lựa chọn giọng nói sau đây trong trường voice_name:

ZephyrTươi sáng PuckRộn ràng CharonCung cấp nhiều thông tin
KoreFirm FenrirDễ kích động LedaTrẻ trung
OrusFirm AoedeBreezy CallirrhoeDễ tính
AutonoeTươi sáng EnceladusBreathy IapetusRõ ràng
UmbrielDễ tính AlgiebaLàm mịn DespinaSmooth
ErinomeClear AlgenibGravelly RasalgethiCung cấp nhiều thông tin
LaomedeiaRộn ràng AchernarMềm AlnilamFirm
SchedarEven GacruxNgười trưởng thành PulcherrimaLạc quan
AchirdThân thiện ZubenelgenubiBình thường VindemiatrixDịu dàng
SadachbiaLively SadaltagerHiểu biết SulafatẤm

Bạn có thể nghe tất cả các lựa chọn về giọng nói trong AI Studio.

Ngôn ngữ được hỗ trợ

Các mô hình TTS tự động phát hiện ngôn ngữ đầu vào. Các ngôn ngữ này hỗ trợ 24 ngôn ngữ sau:

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 Indo (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-INhi-IN Tiếng Marathi (Ấn Độ) mr-IN
Tiếng Tamil (Ấn Độ) ta-IN Tiếng Telugu (Ấn Độ) te-IN

Mô hình được hỗ trợ

Mô hình Loa đơn Nhiều người nói
Bản xem trước Gemini 2.5 Flash TTS ✔️ ✔️
TTS xem trước Gemini 2.5 Pro ✔️ ✔️

Các điểm hạn chế

  • Các mô hình TTS chỉ có thể nhận dữ liệu đầu vào là văn bản và tạo dữ liệu đầu ra là âm thanh.
  • Một phiên TTS có giới hạn cửa sổ ngữ cảnh là 32 nghìn token.
  • Xem phần Ngôn ngữ để biết thông tin về ngôn ngữ được hỗ trợ.

Bước tiếp theo