إنشاء نص إلى كلام (TTS) باستخدام Gemini API


يمكنك أن تطلب من نموذج "تحويل النص إلى كلام" من Gemini إنشاء مخرجات كلامية (صوتية) من طلب نصي. عند استخدام Firebase AI Logic، يمكنك تقديم هذا الطلب مباشرةً من تطبيقك.

يمكن التحكّم في إنشاء ميزة "تحويل النص إلى كلام" (TTS)، ما يعني أنّه يمكنك تقديم النص الدقيق لتحويله إلى كلام. يمكنك أيضًا استخدام اللغة الطبيعية في طلباتك لتحديد أسلوب الملخّص الصوتي ولهجته وسرعته ونبرته. يمكنك اعتبار ميزة "تحويل النص إلى كلام" عكس ميزة "تحويل الكلام إلى نص".

تتوفّر هذه الميزة باستخدام أي من نماذج Gemini -tts، والتي تم تحسينها لإنشاء كلام عالي الجودة وبزمن انتقال منخفض.

باستخدام هذه الميزة، يمكنك إجراء ما يلي:

  • سرد القصص التفاعلي: يمكنك إنشاء كتب مسموعة غامرة أو ألعاب تقمّص أدوار حيث يبدّل النموذج الأصوات لشخصيات مختلفة أو يكيّف نبرته (مثل الهمس في لحظات التشويق أو الضحك على نكتة) لتتناسب مع السرد.

  • تعلُّم اللغات: يمكنك إنشاء أدلة للنطق يمكنها قراءة النص بلهجات إقليمية معيّنة أو بوتيرة أبطأ لمساعدة المتعلّمين على التدرّب على النطق الصعب.

  • قارئات المحتوى المستندة إلى السياق: يمكنك قراءة المقالات الإخبارية أو وصفات الطعام أو منشورات المدوّنات بصوت عالٍ باستخدام شخصية صوتية ونبرة عاطفية تتناسب مع المحتوى (مثل نبرة جادة للأخبار العاجلة أو نبرة دافئة وهادئة لتعليمات الطهي خطوة بخطوة).

يوضّح هذا الدليل كيفية إنشاء كلام من نص مُدخَل باستخدام متحدث واحد أو متحدثين متعددين وكيفية بث الرد الصوتي.

الانتقال إلى الرمز البرمجي الخاص بمتحدّث واحد الانتقال إلى الرمز البرمجي الخاص بمتحدّثين متعددين الانتقال إلى الرمز البرمجي الخاص بالردود المباشرة

مقارنة بين ميزة "تحويل النص إلى كلام" وLive API

يتميّز كلّ من نماذج تحويل النص إلى كلام (TTS) ونماذج Live API بأنّها نماذج لإنشاء الكلام بزمن استجابة منخفض، ويمكن ضبطها لتوفير أصوات ولغات مختلفة للردود. ومع ذلك، فإنها تخدم حالات استخدام مختلفة تمامًا.

  • إنشاء ردود من خلال ميزة "تحويل النص إلى كلام" هو تفاعل أحادي الاتجاه يعتمد على الطلب والرد (إدخال نص، وإخراج صوت). وهو مصمّم للسيناريوهات التي تتطلّب سردًا دقيقًا للنص المقدَّم مع تحكّم دقيق في الأسلوب والصوت، مثل سرد البودكاست أو الكتب المسموعة أو قراءة المقالات بصوت عالٍ.

  • يتيح الجيل Live API البث ثنائي الاتجاه للمحادثات الصوتية في الوقت الفعلي (إدخال الصوت وإخراجه). ويتميّز في سياقات المحادثات الديناميكية التي يقرّر فيها النموذج الكلام المناسب الذي يجب عرضه. يُرجى العِلم أنّ أحدث نماذج Live API تتيح أيضًا إدخال الفيديوهات والصور.

قبل البدء

انقر على مزوّد خدمة Gemini API لعرض المحتوى والرمز البرمجي الخاصَّين بالمزوّد على هذه الصفحة.

إذا لم يسبق لك إجراء ذلك، أكمِل دليل البدء الذي يوضّح كيفية إعداد مشروعك على Firebase وربط تطبيقك بمنصة Firebase وإضافة حزمة تطوير البرامج (SDK) وإعداد خدمة الخلفية لمقدّم خدمة Gemini API الذي اخترته وإنشاء مثيل GenerativeModel.

لاختبار الطلبات وتحسينها، ننصحك باستخدام Google AI Studio.

النماذج التي تتيح هذه الميزة

  • gemini-3.1-flash-tts-preview

تحويل النص إلى كلام

يمكنك إنشاء كلام من نص معيّن باستخدام نموذج تحويل النص إلى كلام من 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) هذه هي دوال تعليق ويجب استدعاؤها من نطاق الكوروتين.

// 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. في 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) هذه هي دوال تعليق ويجب استدعاؤها من نطاق الكوروتين.

// 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) هذه هي دوال تعليق ويجب استدعاؤها من نطاق الكوروتين.

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



القيود والمتطلبات

يُرجى الانتباه إلى القيود والمتطلبات التالية عند استخدام ميزة إنشاء الكلام:

  • تتيح إعدادات مكبّرات الصوت المتعددة استخدام مكبّرَي صوت بالضبط.

  • لا تتوفّر الميزات التالية إلا عند استخدام نماذج Gemini 3.x TTS: البث المباشر وعلامات الصوت واللغات الإضافية التي يتم رصدها تلقائيًا.

القيود المفروضة على "gemini-3.1-flash-tts-preview"

  • عدم اتساق الصوت: قد لا يتطابق الناتج من النموذج دائمًا بشكل صارم مع المتحدث المحدّد إذا كانت نبرة الطلب وسياقه لا يتوافقان مع الملف الشخصي للمتحدث (على سبيل المثال، صوت رجل عميق يحاول التحدث مثل فتاة صغيرة). تأكَّد من أنّ سياق الطلب يتطابق مع الصوت.
  • النتائج الأطول: قد تنخفض جودة الكلام واتساقه في المقاطع الصوتية التي تزيد مدتها عن بضع دقائق. ننصحك بتقسيم الطلبات النصية الطويلة إلى أجزاء أصغر.
  • عرض رموز نصية مميزة من حين لآخر: يعرض النموذج أحيانًا رموزًا نصية مميزة بدلاً من الرموز الصوتية المميزة، ما يؤدي إلى تعذُّر الطلب وظهور الخطأ 500. بما أنّ هذا الخطأ يحدث عشوائيًا في نسبة صغيرة من الطلبات، عليك تنفيذ منطق إعادة المحاولة في تطبيقك.
  • الرفض الخاطئ للمصنِّف: قد تؤدي الطلبات الغامضة إلى فشل مصنِّف تركيب الكلام، ما يؤدي إلى رفض الطلب (PROHIBITED_CONTENT) أو قراءة النموذج لتعليمات الأسلوب بصوت عالٍ. لتجنُّب ذلك، استخدِم طلبًا منظّمًا مع مقدمة واضحة (مثل Audio Profile وDirector's Notes) في بداية الطلب.



الأصوات واللغات المتاحة

تتلقّى نماذج تحويل النص إلى كلام في Gemini نصًا وتنشئ مخرجات صوتية، وبالتالي يكون الردّ هو الكلام الذي تم تركيبه. تسرد الفقرات الفرعية التالية الأصوات واللغات المتوافقة التي يمكن لنماذج تحويل النص إلى كلام في Gemini "التحدّث" بها (أو الردّ بها).

تتوفّر الأصوات بلغات متعدّدة، ما يعني أنّه يمكنك استخدام الصوت نفسه لإنشاء كلام بأي من اللغات المتوافقة. على سبيل المثال، يمكنك ضبط الصوت على Kore وإرسال مجموعة من الطلبات النصية باللغات الإسبانية والهندية والفيتنامية. ستكون الردود كلها بصوت Kore، ولكن بكل لغة من تلك اللغات المختلفة.

أسماء الأصوات

تتيح نماذج تحويل النص إلى كلام (TTS) في Gemini استخدام 30 صوتًا اصطناعيًا مختلفًا بدقة عالية، ولكل منها خصائص مميزة. يمكنك الاطّلاع على قائمة بخيارات أصوات الردود والاستماع إلى عيّنات من كل صوت من خلال توسيع القسم أدناه.

اللغات

يمكن لنماذج تحويل النص إلى كلام في Gemini رصد اللغات التالية تلقائيًا في طلبك النصي. وسيكون الكلام الذي يتم إنشاؤه بهذه اللغة.

يُرجى العِلم أنّه يمكنك اختياريًا ضبط رمز لغة بشكل صريح في إعدادات الكلام.

اللغات المتوافقة مع جميع نماذج إنشاء الصوت
اللغة رمز 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 الفنلندية الفنلندية
الأمهرية صباحًا الغليشيانية gl
الأرمينية hy الجورجية ka
الأذربيجانية az اليونانية el
الباسكية eu الغوجاراتية gu
البيلاروسية be اللغة الكريولية الهايتية ht
البلغارية bg العبرية هو
البورمية my الهنغارية hu
الكتالانية ca الأيسلندية هو
السيبيوانية ceb الجافانية jv
الصينية، المندرينية cmn الكانادا kn
الكرواتية ساعة الكونكانية الكونكانية
التشيكية cs اللاوية lo
الدانماركية da اللاتينية la
الإستونية et اللاتفية اللاتفية
الليتوانية lt اللوكسمبورغية رطل
المقدونية mk المايثلية mai
الملغاشية مليغرام الماليزية ms
المالايالامية ml المنغولية mn
النيبالية ne النرويجية (بوكمول) nb
النرويجية (نينورسك) nn الأوديا أو
البشتو ps الفارسية fa
بنجابي pa الصربية sr
السندية sd السنهالية si
السلوفاكية السلوفاكية السلوفينية 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"