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


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

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

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

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

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

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

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

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

מעבר לקוד של רמקול יחיד מעבר לקוד של כמה רמקולים מעבר לקוד של תגובות בהזרמה

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

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

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

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

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

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

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

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

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

  • gemini-3.1-flash-tts-preview

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

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

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

לפני שמנסים את הדוגמה הזו, צריך להשלים את השלבים שבקטע לפני שמתחילים במדריך הזה כדי להגדיר את הפרויקט והאפליקציה.
בקטע הזה, צריך גם ללחוץ על לחצן של ספק 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: [ResponseModality.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',
  config: 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: [ResponseModality.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',
  config: 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: [ResponseModality.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',
  config: 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]: To speak seriously
  • [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) בתחילת הפרומפט.



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

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

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

שמות הקולות

מודלי ה-TTS‏ Gemini תומכים ב-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 פיליפינית fil
אלבנית sq פינית fi
אמהרית am גליציאנית gl
ארמנית hy גאורגית ka
אזרית az יוונית el
בסקית eu גוג'ארטי gu
בלארוסית be קריאולית האיטית ht
בולגרית bg עברית he
בורמזית 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
  • Kannada: 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?