Generazione di parlato (sintesi vocale)

L'API Gemini può trasformare l'input di testo in audio con un solo oratore o più oratori utilizzando le funzionalità di sintesi vocale (TTS) native. La generazione di sintesi vocale (TTS) è controllabile, il che significa che puoi utilizzare il linguaggio naturale per strutturare le interazioni e guidare lo stile, l'accento, il ritmo e il tono dell'audio.

La funzionalità TTS è diversa dalla sintesi vocale fornita tramite l'API Live, progettata per input e output audio interattivi, non strutturati e multimodali. Mentre l'API Live eccelle in contesti conversazionali dinamici, la sintesi vocale tramite l'API Gemini è pensata per scenari che richiedono una recitazione esatta del testo con un controllo preciso su stile e suono, come la generazione di podcast o audiolibri.

Questa guida mostra come generare audio con un solo oratore e con più oratori dal testo.

Prima di iniziare

Assicurati di utilizzare una variante del modello Gemini 2.5 con funzionalità di sintesi vocale (TTS) native, come elencato nella sezione Modelli supportati. Per risultati ottimali, valuta quale modello si adatta meglio al tuo caso d'uso specifico.

Prima di iniziare a creare, ti consigliamo di testare i modelli TTS Gemini 2.5 in AI Studio.

Sintesi vocale con un solo oratore

Per convertire il testo in audio con un solo oratore, imposta la modalità di risposta su "audio" e passa un oggetto SpeechConfig con VoiceConfig impostato. Dovrai scegliere un nome per la voce tra le voci di output predefinite.

Questo esempio salva l'audio di output del modello in un file 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

Sintesi vocale multilingue

Per l'audio multi-speaker, avrai bisogno di un oggetto MultiSpeakerVoiceConfig con ogni speaker (fino a 2) configurato come SpeakerVoiceConfig. Devi definire ogni speaker con gli stessi nomi utilizzati nel prompt:

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

Controllare lo stile del discorso con i prompt

Puoi controllare lo stile, il tono, l'accento e il ritmo utilizzando prompt in linguaggio naturale sia per la sintesi vocale con una sola voce che con più voci. Ad esempio, in un prompt con un solo oratore, puoi dire:

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

In un prompt con più speaker, fornisci al modello il nome di ogni speaker e la trascrizione corrispondente. Puoi anche fornire indicazioni per ogni oratore singolarmente:

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!

Prova a utilizzare un'opzione vocale che corrisponda allo stile o all'emozione che vuoi trasmettere, per enfatizzarla ancora di più. Nel prompt precedente, ad esempio, il tono affannoso di Encelado potrebbe enfatizzare "stanco" e "annoiato", mentre il tono allegro di Puck potrebbe completare "entusiasta" e "felice".

Generazione di un prompt per la conversione in audio in corso…

I modelli TTS restituiscono solo audio, ma puoi utilizzare altri modelli per generare prima una trascrizione, quindi passare la trascrizione al modello TTS per la lettura ad alta voce.

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

Opzioni vocali

I modelli TTS supportano le seguenti 30 opzioni vocali nel campo voice_name:

Zephyr - Luminoso Puck: Upbeat Caronte: informativa
Kore -- Firm Fenrir: eccitabile Leda - Giovane
Orus -- Azienda Aoede - Breezy Callirrhoe: informale
Autonoe - Luminosità Enceladus - Breathy Iapetus -- Cancella
Umbriel: tranquillo Algieba - Smooth Despina -- Smooth
Erinome -- Sereno Algenib - Gravelly Rasalgethi -- Priorità informativa
Laomedeia - Upbeat Achernar - Soft Alnilam -- Firm
Schedar -- Even Gacrux - Per adulti Pulcherrima -- Avanti
Achird - Amichevole Zubenelgenubi - Casual Vindemiatrix - Gentle
Sadachbia - Vivace Sadaltager -- Knowledgeable Sulafat - Calda

Puoi ascoltare tutte le opzioni vocali in AI Studio.

Lingue supportate

I modelli di sintesi vocale rilevano automaticamente la lingua di input. Supportano le seguenti 24 lingue:

Lingua Codice BCP-47 Lingua Codice BCP-47
Arabo (egiziano) ar-EG Tedesco (Germania) de-DE
Inglese (USA) en-US Spagnolo (Stati Uniti) es-US
Francese (Francia) fr-FR Hindi (India) hi-IN
Indonesiano (Indonesia) id-ID Italiano (Italia) it-IT
Giapponese (Giappone) ja-JP Coreano (Corea) ko-KR
Portoghese (Brasile) pt-BR Russo (Russia) ru-RU
Olandese (Paesi Bassi) nl-NL Polacco (Polonia) pl-PL
Thailandese (Thailandia) th-TH Turco (Turchia) tr-TR
Vietnamita (Vietnam) vi-VN Rumeno (Romania) ro-RO
Ucraino (Ucraina) uk-UA Bengalese (Bangladesh) bn-BD
Inglese (India) Bundle en-IN e hi-IN Marathi (India) mr-IN
Tamil (India) ta-IN Telugu (India) te-IN

Modelli supportati

Modello Unico interlocutore Multispeaker
Gemini 2.5 Flash Preview TTS ✔️ ✔️
Anteprima della sintesi vocale di Gemini 2.5 Pro ✔️ ✔️

Limitazioni

  • I modelli TTS possono ricevere solo input di testo e generare output audio.
  • Una sessione TTS ha un limite di finestra contestuale di 32.000 token.
  • Consulta la sezione Lingue per verificare il supporto delle lingue.

Passaggi successivi