יצירת דיבור (המרת טקסט לדיבור)

‫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

שליטה בסגנון הדיבור באמצעות הנחיות

אתם יכולים לשלוט בסגנון, בטון, במבטא ובקצב באמצעות הנחיות בשפה טבעית, גם בהמרת טקסט לדיבור עם דובר אחד וגם עם כמה דוברים. לדוגמה, בהנחיה עם דובר אחד, אפשר להגיד:

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 CharonInformative
Kore -- Firm Fenrirמתלהב Leda -- Youthful
Orus -- Firm AoedeBreezy Callirrhoeנינוח
Autonoe -- Bright Enceladus -- Breathy Iapetus -- Clear
Umbrielנינוח Algieba -- Smooth Despina -- Smooth
Erinome -- Clear Algenib -- מחוספס Rasalgethi -- Informative
Laomedeia -- Upbeat Achernar -- Soft Alnilam -- Firm
Schedar -- Even GacruxMature Pulcherrimaהעברה
Achird -- Friendly Zubenelgenubiשגרתי Vindemiatrix -- Gentle
SadachbiaLively Sadaltager -- Knowledgeable Sulafat -- חמה

אפשר לשמוע את כל האפשרויות של הקול ב-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

מודלים נתמכים

דגם דובר יחיד מערכת רמקולים
תצוגה מקדימה של Gemini ‎2.5 Flash TTS ✔️ ✔️
תצוגה מקדימה של Gemini ‎2.5 Pro TTS ✔️ ✔️

מגבלות

  • מודלים של TTS יכולים לקבל רק קלט טקסט ולהפיק פלט אודיו.
  • לסשן TTS יש מגבלה של 32,000 טוקנים בחלון ההקשר.
  • בקטע שפות מפורטות השפות הנתמכות.

המאמרים הבאים