יצירת המרת טקסט לדיבור (TTS) באמצעות Gemini API


אתם יכולים לבקש ממודל TTS של Gemini ליצור פלט דיבור (אודיו) מפרומפט טקסטואלי. כשמשתמשים ב-Firebase AI Logic, אפשר לשלוח את הבקשה הזו ישירות מהאפליקציה.

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

התכונה הזו זמינה בכל אחד מהמודלים של Gemini -tts, שמותאמים ליצירת דיבור באיכות גבוהה ובזמן אחזור קצר.

היכולת הזו מאפשרת לכם:

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

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

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

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

דילוג לקוד של דובר יחיד דילוג לקוד של כמה דוברים דילוג לקוד של תשובות בסטרימינג

השוואה בין TTS לבין Live API

גם מודלים של המרת טקסט לדיבור (TTS) וגם מודלים של Live API הם מודלים ליצירת דיבור עם זמן אחזור קצר, שאפשר להגדיר אותם לשפות ולקולות שונים של תשובות. עם זאת, הם משמשים למטרות שונות מאוד.

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

  • הדור Live API תומך בסטרימינג דו-כיווני לשיחות קוליות בזמן אמת (קלט קולי, פלט קולי). הוא מתאים במיוחד להקשרים דינמיים של שיחה, שבהם המודל מחליט מה הדיבור המתאים להחזיר. שימו לב שהמודלים העדכניים של Live API תומכים גם בקלט של וידאו ותמונות.

לפני שמתחילים

כדי לראות תוכן וקוד שספציפיים לספק, לוחצים על הספק Gemini API בדף הזה.

אם עדיין לא עשיתם את זה, אתם צריכים לפעול לפי המדריך לתחילת העבודה, שבו מוסבר איך להגדיר את הפרויקט ב-Firebase, לקשר את האפליקציה ל-Firebase, להוסיף את ה-SDK, להפעיל את שירות הקצה העורפי של ספק ה-Gemini API שבחרתם וליצור מכונה של GenerativeModel.

כדי לבדוק את ההנחיות ולשפר אותן, מומלץ להשתמש ב-Google AI Studio.

מודלים שתומכים ביכולת הזו

  • gemini-3.1-flash-tts-preview

יצירת דיבור מטקסט

אתם יכולים ליצור דיבור מטקסט שאתם מספקים באמצעות מודל TTS של Gemini.

יצירת דיבור עם דובר אחד

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על כפתור של ספק Gemini API שבחרתם כדי לראות תוכן ספציפי לספק בדף הזה.

אתם יכולים להגדיר את המודל כך שיפיק פלט אודיו בקול אחד.

בGenerationConfig, צריך לכלול את הפרטים הבאים:

מפעילים את generateContent באמצעות פרומפט טקסטואלי. המודל מחזיר נתוני אודיו גולמיים בפורמט PCM בחלקי התשובה.

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

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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

ב-Java, השיטות להעברת נתונים בסטרימינג ב-SDK הזה מחזירות סוג Publisher מספריית 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: [ResponseModalities.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',
  generationConfig: 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);
    }
  }
}

יצירת דיבור עם כמה דוברים

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על כפתור של ספק Gemini API שבחרתם כדי לראות תוכן ספציפי לספק בדף הזה.

אתם יכולים להגדיר למודל להשתמש בקולות שונים לדוברים שונים בטקסט. התכונה הזו שימושית ליצירת אודיו לדיאלוגים או לשיחות.

  1. יוצרים MultiSpeakerVoiceConfig שממפה שמות של דוברים (שבהם תשתמשו בהנחיה) לשמות ספציפיים של קולות לתשובות (לדוגמה, Kore).

    ההגדרה של כמה דוברים תומכת ב-2 דוברים בדיוק.

  2. בGenerationConfig, צריך לכלול את הפרטים הבאים:

    • מגדירים את responseModalities כך שיכלול את AUDIO.

    • מגדירים SpeechConfig עם הפרטים הבאים:

  3. בהנחיה, מציינים מי הדובר באמצעות שמות הדוברים בתור קידומות (לדוגמה, Joe: Hello. Jane: Hi.).

מפעילים את generateContent באמצעות פרומפט טקסטואלי. המודל מחזיר נתוני אודיו גולמיים בפורמט PCM בחלקי התשובה.

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

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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

ב-Java, השיטות להעברת נתונים בסטרימינג ב-SDK הזה מחזירות סוג Publisher מספריית 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: [ResponseModalities.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',
  generationConfig: 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);
    }
  }
}

הצגת התשובה באופן שוטף

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים בקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על כפתור של ספק Gemini API שבחרתם כדי לראות תוכן ספציפי לספק בדף הזה.

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

אפשר להשתמש בסטרימינג של דיבור שנוצר גם בהגדרות של דובר יחיד וגם בהגדרות של כמה דוברים. הוא נתמך רק כשמשתמשים במודלים של Gemini 3.x TTS.

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

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

ב-Kotlin, השיטות ב-SDK הזה הן פונקציות השהיה וצריך לקרוא להן מהיקף 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

ב-Java, השיטות להעברת נתונים בסטרימינג ב-SDK הזה מחזירות סוג Publisher מספריית 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: [ResponseModalities.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',
  generationConfig: 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);
    }
}



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

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

בסעיפי המשנה הבאים, שעוסקים במבנה ההנחיה ובתגי אודיו, מתוארות הנחיות כלליות. במדריך הזה מוסבר בהרחבה איך לכתוב הנחיות.

מבנה ההנחיה

כדי לקבל את התוצאות הכי טובות, כדאי לכלול בהנחיה את הרכיבים הבאים:

  • ‫Audio Profile: תיאור הפרסונה, הזהות העיקרית והארכיטיפ של הדובר (לדוגמה, A warm, professional narrator).

  • ‫Scene: תיאור הסביבה והאווירה הרגשית (לדוגמה, In a quiet library או Amidst a noisy crowd).

  • ‫Director's Notes: תיאור הרגש, הקצב, הסגנון והמבטא (לדוגמה, Speak slowly and with mystery).

  • ‫Sample Context: נותנים למודל נקודת התחלה (לדוגמה, The speaker is greeting a close friend).

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

דוגמה לפרומפט:

[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!

תגי אודיו

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

תגי אודיו נתמכים רק כשמשתמשים במודלים של Gemini 3.x TTS.

תגים נפוצים:

  • ‫[whispers]: כדי לדבר בלחישה
  • ‫[laughs]: כדי להוסיף צחוק
  • ‫[giggles]: כדי להוסיף צחוקים
  • ‫[sighs]: כדי להוסיף אנחה
  • [gasp]: כדי להוסיף נשימה עמוקה
  • ‫[shouting]: לצעוק
  • ‫[excited]: לדבר בהתלהבות
  • ‫[serious]: לדבר ברצינות
  • [sighs whispers]: רגשות משולבים (אפשר לשלב תגים)

כשמשתמשים בתגי אודיו, חשוב לשים לב לנקודות הבאות:

  • אין רשימה מלאה: אין רשימה קבועה של תגים נתמכים. אתם יכולים להתנסות ברגשות ובהבעות שונים (כמו [bored], [sarcastically] או אפילו [like dracula]) כדי לראות איך הפלט משתנה.

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

דוגמה לפרומפט:

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



מגבלות ודרישות

כשמשתמשים ביצירת דיבור, חשוב לשים לב למגבלות ולדרישות הבאות:

  • ההגדרה של כמה דוברים תומכת ב-2 דוברים בדיוק.

  • התכונות הבאות נתמכות רק כשמשתמשים במודלים של Gemini 3.x TTS: סטרימינג, תגי אודיו ושפות נוספות שזוהו באופן אוטומטי.

אילוצים של gemini-3.1-flash-tts-preview

  • חוסר עקביות בקול: יכול להיות שהפלט של המודל לא תמיד יתאים בדיוק לדובר שנבחר, אם הטון וההקשר של ההנחיה לא תואמים לפרופיל של הדובר (לדוגמה, קול גברי עמוק שמנסה לדבר כמו ילדה צעירה). חשוב לוודא שההקשר של ההנחיה תואם לקול.
  • פלט ארוך יותר: איכות הדיבור והעקביות עלולות להשתנות באודיו שאורכו יותר מכמה דקות. מומלץ לפצל פרומפטים טקסטואליים ארוכים לחלקים קטנים יותר.
  • החזרה של אסימוני טקסט מדי פעם: המודל מחזיר מדי פעם אסימוני טקסט במקום אסימוני אודיו, מה שגורם לבקשה להיכשל עם שגיאה 500. מכיוון שהשגיאה הזו מתרחשת באופן אקראי באחוז קטן מהבקשות, כדאי להטמיע באפליקציה לוגיקה של ניסיון חוזר.
  • דחיות שגויות של המסווג: הנחיות מעורפלות עלולות לגרום למסווג של סינתזת הדיבור להיכשל, וכתוצאה מכך הבקשה תידחה (PROHIBITED_CONTENT) או שהמודל יקריא בקול את ההוראות לגבי הסגנון. כדי למנוע את זה, השתמשו בהנחיה מובנית עם הוראות מקדימות ברורות (כמו Audio Profile ו-Director's Notes) בתחילת ההנחיה.



שפות וקולות נתמכים

המודלים של Gemini להמרת טקסט לדיבור מקבלים קלט טקסט ויוצרים פלט אודיו, כך שהתשובה היא הדיבור המסונתז עצמו. בסעיפי המשנה הבאים מפורטים הקולות והשפות הנתמכים שבהם מודלי ה-TTS של Gemini יכולים "לדבר" (או להגיב).

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

שמות הקולות

המודלים של Gemini TTS תומכים ב-30 קולות HD מסונתזים שונים, שלכל אחד מהם מאפיינים ייחודיים. כדי לראות רשימה של אפשרויות קוליות לתשובות ולשמוע הדגמות של כל קול, אתם יכולים להרחיב את הקטע שבהמשך.

שפות

המודלים של Gemini TTS יכולים לזהות באופן אוטומטי את השפות הבאות בפרומפט הטקסטואלי שלכם. הדיבור שייווצר יהיה בשפה הזו.

שימו לב שאפשר גם להגדיר במפורש קוד שפה בהגדרות הדיבור.

השפות שנתמכות בכל המודלים ליצירת אודיו
שפה קוד 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
שפות נוספות שנתמכות במודלים ליצירת אודיו בגרסה 3.x
שפה קוד BCP-47 שפה קוד BCP-47
אפריקאנס af פיליפינית פיליפינית
אלבנית sq פינית fi
אמהרית am גליציאנית gl
ארמנית hy גאורגית ka
אזרית az יוונית el
בסקית eu גוג'ארטי gu
בלארוסית be קריאולית האיטית ht
בולגרית bg עברית הוא
בורמזית my הונגרית hu
קטלאנית ca איסלנדית is
סבואנו ceb ג'אוונית jv
סינית, מנדרינית cmn קנאדה kn
קרואטית שעה קונקאני kok
צ'כית cs לאו lo
דנית da לטינית la
אסטונית et לטבית lv
ליטאית lt לוקסמבורגית lb
מקדונית mk מאיתילי mai
מלגשית מ"ג מלאית ms
מליאלאם ml מונגולית mn
נפאלית ne נורווגית (ספרותית) nb
נורווגית (נינורסק) nn אודיה או
פשטו ps פרסית fa
פנג'אבי pa סרבית sr
סינדהית sd סינהאלה si
סלובקית sk סלובנית sl
סווהילי sw שוודית sv
אורדו ur

(אופציונלי) הגדרת קוד שפה באופן מפורש

אם לא תציינו קוד שפה בהגדרות הדיבור, המודל יזהה אוטומטית את השפה בפרומפט הטקסטואלי.

עם זאת, אפשר להגדיר את השפה באופן מפורש (באמצעות הפרמטר languageCode בהגדרת הדיבור). כדי לעשות את זה, צריך להשתמש באחד מקודי הלוקאל הבאים שנתמכים בתקן BCP-47:

  • ערבית: ar-XA
  • בנגלית: bn-IN
  • סינית (מנדרינית): cmn-CN
  • הולנדית: nl-NL
  • אנגלית: en-US, ‏ en-GB, ‏ en-AU, ‏ en-IN
  • צרפתית: fr-FR, fr-CA
  • גרמנית: de-DE
  • גוג'ראטית: gu-IN
  • הינדית: hi-IN
  • אינדונזית: id-ID
  • איטלקית: it-IT
  • יפנית: ja-JP
  • קנאדה: kn-IN
  • קוריאנית: ko-KR
  • מלאיאלאם: ml-IN
  • מראטהית: mr-IN
  • פולנית: pl-PL
  • פורטוגזית: pt-BR
  • רוסית: ru-RU
  • ספרדית: es-US, es-ES
  • טמילית: ta-IN
  • טלוגו: te-IN
  • תאילנדית: th-TH
  • טורקית: tr-TR
  • וייטנאמית: vi-VN



מה עוד אפשר לעשות?

לנסות יכולות אחרות

איך לשלוט ביצירת התוכן

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

מידע נוסף על המודלים הנתמכים

מידע ולמידה על המודלים שזמינים לתרחישי שימוש שונים, המכסות והתמחור שלהם.


שליחת משוב על חוויית השימוש ב-Firebase AI Logic