การสร้างเสียงพูด (การอ่านออกเสียงข้อความ)

Gemini API สามารถเปลี่ยนอินพุตข้อความเป็นเสียงของลำโพงคนเดียวหรือหลายคน โดยใช้ความสามารถในการสร้างข้อความเป็นเสียง (TTS) แบบเนทีฟ การสร้างการอ่านออกเสียงข้อความ (TTS) เป็นแบบควบคุมได้ ซึ่งหมายความว่าคุณสามารถใช้ภาษาธรรมชาติเพื่อจัดโครงสร้างการโต้ตอบและกำหนดสไตล์ สำเนียง จังหวะ และโทนเสียงของเสียงได้

ความสามารถของ TTS แตกต่างจากการสร้างคำพูดที่ให้บริการผ่าน Live API ซึ่งออกแบบมาสำหรับเสียงแบบอินเทอร์แอกทีฟที่ไม่มีโครงสร้าง รวมถึงอินพุตและเอาต์พุตแบบมัลติโมดัล แม้ว่า Live API จะยอดเยี่ยม ในบริบทการสนทนาแบบไดนามิก แต่ TTS ผ่าน Gemini API ได้รับการปรับแต่งสำหรับสถานการณ์ที่ต้องมีการอ่านข้อความที่แน่นอนพร้อมการควบคุม สไตล์และเสียงอย่างละเอียด เช่น การสร้างพอดแคสต์หรือหนังสือเสียง

คู่มือนี้จะแสดงวิธีสร้างเสียงแบบผู้พูดคนเดียวและแบบผู้พูดหลายคนจากข้อความ

ก่อนเริ่มต้น

ตรวจสอบว่าคุณใช้โมเดล Gemini 2.5 ที่มีความสามารถในการอ่านออกเสียงข้อความ (TTS) แบบเนทีฟตามที่ระบุไว้ในส่วนโมเดลที่รองรับ โปรดพิจารณาว่าโมเดลใดเหมาะกับกรณีการใช้งานเฉพาะของคุณมากที่สุดเพื่อให้ได้ผลลัพธ์ที่ดีที่สุด

คุณอาจเห็นว่าการทดสอบโมเดล TTS ของ Gemini 2.5 ใน AI Studio มีประโยชน์ก่อนที่จะเริ่มสร้าง

การอ่านออกเสียงข้อความแบบผู้พูดคนเดียว

หากต้องการแปลงข้อความเป็นเสียงแบบลำโพงเดียว ให้ตั้งค่ารูปแบบการตอบกลับเป็น "เสียง" และส่งออบเจ็กต์ SpeechConfig ที่ตั้งค่า VoiceConfig คุณจะต้องเลือกชื่อเสียงจากเสียงเอาต์พุตที่สร้างไว้ล่วงหน้า

ตัวอย่างนี้จะบันทึกเสียงเอาต์พุตจากโมเดลในไฟล์ Wave

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

การอ่านออกเสียงข้อความแบบหลายเสียง

สำหรับเสียงแบบหลายลำโพง คุณจะต้องมีออบเจ็กต์ MultiSpeakerVoiceConfig ที่กำหนดค่าลำโพงแต่ละตัว (สูงสุด 2 ตัว) เป็น SpeakerVoiceConfig คุณจะต้องกําหนดแต่ละ speaker โดยใช้ชื่อเดียวกันกับที่ใช้ในพรอมต์ ดังนี้

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

การควบคุมรูปแบบคำพูดด้วยพรอมต์

คุณควบคุมสไตล์ น้ำเสียง สำเนียง และจังหวะได้โดยใช้พรอมต์ภาษาธรรมชาติ สำหรับ TTS แบบเสียงเดียวและหลายเสียง ตัวอย่างเช่น ในพรอมต์ที่มีผู้พูดคนเดียว คุณอาจพูดว่า

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

ในพรอมต์ที่มีผู้พูดหลายคน ให้ระบุชื่อของผู้พูดแต่ละคนและ ข้อความถอดเสียงที่เกี่ยวข้อง นอกจากนี้ คุณยังให้คำแนะนำแก่ผู้พูดแต่ละคนได้ด้วย โดยทำดังนี้

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!

ลองใช้ตัวเลือกเสียงที่สอดคล้องกับสไตล์หรืออารมณ์ที่คุณต้องการสื่อ เพื่อเน้นย้ำให้ชัดเจนยิ่งขึ้น เช่น ในพรอมต์ก่อนหน้า เสียงลมของ Enceladus อาจเน้นคำว่า "เหนื่อย" และ "เบื่อ" ในขณะที่โทนเสียงที่ร่าเริงของ Puck อาจเสริมคำว่า "ตื่นเต้น" และ "มีความสุข"

กำลังสร้างพรอมต์เพื่อแปลงเป็นเสียง

โมเดล TTS จะแสดงผลเฉพาะเสียง แต่คุณสามารถใช้โมเดลอื่นๆ เพื่อสร้างข้อความถอดเสียงก่อน แล้วส่งข้อความถอดเสียงนั้นไปยังโมเดล TTS เพื่ออ่านออกเสียง

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();

ตัวเลือกเสียง

โมเดล TTS รองรับตัวเลือกเสียง 30 แบบต่อไปนี้ในฟิลด์ voice_name

Zephyr -- Bright Puck -- Upbeat Charon - ให้ข้อมูล
Kore -- Firm Fenrir -- ตื่นเต้นง่าย Leda -- วัยรุ่น
Orus -- Firm Aoede -- Breezy Callirrhoe -- สบายๆ
Autonoe -- Bright Enceladus -- Breathy Iapetus -- Clear
Umbriel - สบายๆ Algieba - Smooth Despina -- Smooth
Erinome -- ล้าง Algenib -- แหบเล็กน้อย Rasalgethi -- ให้ข้อมูล
Laomedeia -- สนุกสนาน Achernar - Soft Alnilam - Firm
Schedar -- Even Gacrux -- ผู้ใหญ่ Pulcherrima -- มั่นใจ
Achird -- เป็นมิตร Zubenelgenubi - สบายๆ Vindemiatrix -- อ่อนโยน
Sadachbia -- มีชีวิตชีวา Sadaltager -- มีความรู้ Sulafat -- Warm

คุณฟังตัวเลือกเสียงทั้งหมดได้ใน AI Studio

ภาษาที่รองรับ

โมเดล TTS จะตรวจหาภาษาที่ป้อนโดยอัตโนมัติ โดยรองรับภาษาต่อไปนี้ 24 ภาษา

ภาษา รหัส BCP-47 ภาษา รหัส BCP-47
อาหรับ (อียิปต์) ar-EG เยอรมัน (เยอรมนี) de-DE
อังกฤษ (อเมริกัน) en-US สเปน (สหรัฐอเมริกา) es-US
ฝรั่งเศส (ฝรั่งเศส) fr-FR ฮินดี (อินเดีย) hi-IN
อินโดนีเซีย (อินโดนีเซีย) id-ID อิตาลี (อิตาลี) it-IT
ญี่ปุ่น (ญี่ปุ่น) ja-JP เกาหลี (เกาหลี) ko-KR
โปรตุเกส (บราซิล) pt-BR รัสเซีย (รัสเซีย) ru-RU
ดัตช์ (เนเธอร์แลนด์) nl-NL โปแลนด์ (โปแลนด์) pl-PL
ไทย (ประเทศไทย) th-TH ตุรกี (ตุรกี) tr-TR
เวียดนาม (เวียดนาม) vi-VN โรมาเนีย (โรมาเนีย) ro-RO
ยูเครน (ยูเครน) uk-UA เบงกาลี (บังกลาเทศ) bn-BD
อังกฤษ (อินเดีย) แพ็กเกจ en-IN และ hi-IN มราฐี (อินเดีย) mr-IN
ทมิฬ (อินเดีย) ta-IN เตลูกู (อินเดีย) te-IN

โมเดลที่รองรับ

รุ่น ผู้พูดคนเดียว Multispeaker
TTS ของ Gemini 2.5 Flash (เวอร์ชันตัวอย่าง) ✔️ ✔️
TTS ของ Gemini 2.5 Pro เวอร์ชันตัวอย่าง ✔️ ✔️

ข้อจำกัด

  • โมเดล TTS รับได้เฉพาะข้อความที่ป้อนและสร้างเอาต์พุตเสียงเท่านั้น
  • เซสชัน TTS มีขีดจำกัดหน้าต่างบริบทอยู่ที่ 32,000 โทเค็น
  • ดูส่วนภาษาเพื่อดูการรองรับภาษา

ขั้นตอนถัดไป