Gemini API'yi kullanarak metin okuma (TTS) oluşturma


Gemini TTS modelinden metin isteminden konuşma (ses) çıkışı oluşturmasını isteyebilirsiniz. Firebase AI Logic'ı kullandığınızda bu isteği doğrudan uygulamanızdan gönderebilirsiniz.

Metin okuma (TTS) üretimi kontrol edilebilir. Yani konuşma sentezi için tam metni siz sağlarsınız. Ayrıca, ses çıkışının stilini, aksanını, hızını ve tonunu yönlendirmek için istemlerinizde doğal dil kullanabilirsiniz. TTS'yi transkripsiyonun (konuşmayı metne dönüştürme) tersi olarak düşünebilirsiniz.

Bu özellik, yüksek kaliteli ve düşük gecikmeli konuşma üretimi için optimize edilmiş Gemini -tts modellerinden herhangi biriyle kullanılabilir.

Bu özellik sayesinde şunları yapabilirsiniz:

  • Etkileşimli hikaye anlatımı: Modelin farklı karakterler için ses değiştirdiği veya tonunu (ör. gerilim anında fısıldama ya da bir şakaya gülme) anlatıya uyacak şekilde uyarladığı sürükleyici sesli kitaplar ya da rol yapma oyunları oluşturun.

  • Dil öğrenme: Öğrencilerin zor telaffuzları pratik etmesine yardımcı olmak için metinleri belirli bölgesel aksanlarla veya daha yavaş bir tempoda okuyabilen telaffuz kılavuzları oluşturun.

  • Bağlama duyarlı içerik okuyucular: Haber makalelerini, yemek tariflerini veya blog yayınlarını, içeriğe uygun bir ses karakteri ve duygusal ton kullanarak sesli okuyun (ör. son dakika haberleri için ciddi bir ton veya adım adım yemek pişirme talimatları için sıcakkanlı ve sabırlı bir ton).

Bu kılavuzda, tek veya birden fazla konuşmacı içeren metin girişinden nasıl konuşma oluşturulacağı ve sesli yanıtın nasıl yayınlanacağı gösterilmektedir.

Tek hoparlörlü kod bölümüne git Çok hoparlörlü kod bölümüne git Akış yanıtları için kod bölümüne git

TTS ile Live API arasındaki karşılaştırma

Hem metin okuma (TTS) modelleri hem de Live API modelleri, düşük gecikmeli, farklı yanıt sesleri ve dilleri için yapılandırılabilen konuşma üreten modellerdir. Ancak bu iki ürünün kullanım alanları birbirinden çok farklıdır.

  • Metin okuma (TTS) oluşturma, tek yönlü bir istek-yanıt etkileşimidir (metin girişi, ses çıkışı). Bu model, stil ve ses üzerinde ayrıntılı kontrolle birlikte sağlanan metnin tam olarak okunmasını gerektiren senaryolar için tasarlanmıştır. Örneğin, podcast anlatımı, sesli kitaplar veya makaleleri sesli okuma gibi.

  • Live API nesil, anlık sesli sohbetler (ses girişi, ses çıkışı) için çift yönlü akışı destekler. Modelin, döndürülecek uygun konuşmaya karar verdiği dinamik sohbet bağlamlarında mükemmel performans gösterir. En yeni Live API modellerin video ve resim girişini de desteklediğini unutmayın.

Başlamadan önce

Sağlayıcıya özel içeriği ve kodu bu sayfada görüntülemek için Gemini API sağlayıcınızı tıklayın.

Henüz yapmadıysanız başlangıç kılavuzunu tamamlayın. Bu kılavuzda Firebase projenizi nasıl ayarlayacağınız, uygulamanızı Firebase'e nasıl bağlayacağınız, SDK'yı nasıl ekleyeceğiniz, seçtiğiniz Gemini API sağlayıcısı için arka uç hizmetini nasıl başlatacağınız ve GenerativeModel örneğini nasıl oluşturacağınız açıklanmaktadır.

İstemlerinizi test etmek ve üzerinde yineleme yapmak için Google AI Studio kullanmanızı öneririz.

Bu özelliği destekleyen modeller

  • gemini-3.1-flash-tts-preview

Metinden konuşma oluşturma

Gemini TTS modeli kullanarak sağlanan metinden konuşma üretebilirsiniz.

Tek bir konuşmacıyla konuşma üretme

Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.
Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Modeli, tek bir ses kullanarak ses çıkışı verecek şekilde yapılandırabilirsiniz.

GenerationConfig içinde şunları ekleyin:

Metin isteminizle generateContent'ı arayın. Model, yanıttaki bölümlerde ham PCM ses verilerini döndürür.

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'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.

// 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'da, bu SDK'daki akış yöntemleri Reactive Streams kitaplığından bir Publisher türü döndürür.

// 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);
    }
  }
}

Birden fazla konuşmacıyla konuşma oluşturma

Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.
Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Modeli, metindeki farklı konuşmacılar için farklı sesler kullanacak şekilde yapılandırabilirsiniz. Bu özellik, diyaloglar veya sohbetler için ses üretirken kullanışlıdır.

  1. Konuşmacı adlarını (isteminizde kullanacağınız) belirli MultiSpeakerVoiceConfig (örneğin, Kore) ile eşleyen bir yanıt ses adı oluşturun.

    Çok hoparlörlü yapılandırma tam olarak 2 hoparlörü destekler.

  2. GenerationConfig içinde şunları ekleyin:

    • responseModalities öğesini AUDIO'ı içerecek şekilde ayarlayın.

    • Aşağıdaki bilgileri kullanarak bir SpeechConfig yapılandırın:

  3. İsteminizde, konuşmacı adlarını ön ek olarak (ör. Joe: Hello. Jane: Hi.) kullanarak kimin konuştuğunu belirtin.

Metin isteminizle generateContent'ı arayın. Model, yanıttaki bölümlerde ham PCM ses verilerini döndürür.

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'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.

// 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'da, bu SDK'daki akış yöntemleri Reactive Streams kitaplığından bir Publisher türü döndürür.

// 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);
    }
  }
}

Yanıtı akış şeklinde gösterme

Bu örneği denemeden önce projenizi ve uygulamanızı ayarlamak için bu kılavuzun Başlamadan önce bölümünü tamamlayın.
Bu bölümde, seçtiğiniz Gemini API sağlayıcı için bir düğmeyi de tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Sesli yanıtın tamamlanmasını beklemek yerine, oluşturuldukça akışını sağlayarak daha hızlı etkileşimler ve daha düşük gecikme elde edebilirsiniz.

Oluşturulan konuşmanın akışı hem tek konuşmacılı hem de çok konuşmacılı yapılandırmalarda desteklenir. Yalnızca Gemini 3.x TTS modelleri kullanılırken desteklenir.

Konuşma yanıtını yayınlamak için generateContent yerine generateContentStream işlevini çağırın ve gelen parçaları işleyin. Aşağıdaki örneklerde, tek konuşmacılı bir yanıtın nasıl yayınlanacağı gösterilmektedir:

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'de bu SDK'daki yöntemler askıya alma işlevleridir ve Coroutine kapsamından çağrılmaları gerekir.

// 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'da, bu SDK'daki akış yöntemleri Reactive Streams kitaplığından bir Publisher türü döndürür.

// 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);
    }
}



İstemlerle konuşma çıkışını kontrol etme

Belirli istem tekniklerini kullanarak oluşturulan konuşmanın tonunu, hızını ve stilini etkileyebilirsiniz.

İstem yapısı ve ses etiketleri ile ilgili aşağıdaki alt bölümlerde üst düzey rehberlik sağlanmaktadır. Ayrıntılı bilgi için bu istem kılavuzuna bakın.

İstem yapısı

En iyi sonuçları elde etmek için isteminizi aşağıdaki bileşenlerle yapılandırın:

  • Audio Profile: Konuşmacının kişiliğini, temel kimliğini ve arketipini (örneğin, A warm, professional narrator) açıklayın.

  • Scene: Ortamı ve duygusal atmosferi açıklayın (örneğin, In a quiet library veya Amidst a noisy crowd).

  • Director's Notes: Duyguyu, hızı, stili ve aksanı açıklayın (örneğin, Speak slowly and with mystery).

  • Sample Context: Modele bir başlangıç noktası verin (örneğin, The speaker is greeting a close friend).

  • Transkript: Konuşulacak asıl metin. En iyi performans için metnin yazılı üslubunun ve bağlamının ses profili ve yönetmen notlarıyla uyumlu olduğundan emin olun.

Örnek istem:

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

Ses etiketleri

Modelin performansını yönlendirmek için biçimlendirme etiketlerini doğrudan metin isteminize ekleyebilirsiniz.

Ses etiketleri yalnızca Gemini 3.x TTS modelleri kullanılırken desteklenir.

En çok tercih edilen etiketler şunlardır:

  • [whispers]: Fısıltıyla konuşmak için
  • [laughs]: Kahkaha eklemek için
  • [giggles]: Kahkaha eklemek için
  • [sighs]: İç çekme eklemek için
  • [gasp]: Şaşkınlık ifadesi eklemek için
  • [shouting]: Bağırmak
  • [excited]: Heyecanla konuşmak
  • [serious]: Ciddi bir şekilde konuşmak
  • [sighs whispers]: Birleştirilmiş duygular (etiketleri birleştirebilirsiniz)

Ses etiketlerini kullanırken aşağıdakilere dikkat edin:

  • Kapsamlı liste yok: Desteklenen etiketlerin sabit bir listesi yoktur. Çıkışın nasıl değiştiğini görmek için farklı duygular ve ifadelerle (ör. [bored], [sarcastically] veya [like dracula]) denemeler yapabilirsiniz.

  • İngilizce olmayan metin istemi: Metin isteminiz İngilizce değilse en iyi sonuçları elde etmek için İngilizce ses etiketleri kullanmaya devam etmelisiniz.

Örnek istem:

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



Sınırlamalar ve şartlar

Konuşma üretimi özelliğini kullanırken aşağıdaki sınırlamaları ve koşulları göz önünde bulundurun:

  • Çok hoparlörlü yapılandırma tam olarak 2 hoparlörü destekler.

  • Aşağıdaki özellikler yalnızca Gemini 3.x TTS modelleri kullanılırken desteklenir: akış, ses etiketleri ve otomatik olarak algılanan ek diller.

gemini-3.1-flash-tts-preview için kısıtlamalar

  • Ses tutarsızlığı: İsteminizin tonu ve bağlamı, konuşmacının profiliyle eşleşmiyorsa (ör. genç bir kız gibi konuşmaya çalışan derin bir erkek sesi) modelin çıktısı her zaman seçilen konuşmacıyla tam olarak eşleşmeyebilir. İstem bağlamınızın sesle eşleştiğinden emin olun.
  • Daha uzun çıktılar: Konuşma kalitesi ve tutarlılığı, birkaç dakikadan uzun seslerde değişebilir. Uzun metin istemlerini daha küçük parçalara bölmenizi öneririz.
  • Bazen metin jetonları döndürülüyor: Model bazen ses jetonları yerine metin jetonları döndürdüğünden istek, 500 hatasıyla başarısız oluyor. Bu durum, isteklerin küçük bir yüzdesinde rastgele gerçekleştiği için uygulamanızda yeniden deneme mantığı uygulamanız gerekir.
  • Sınıflandırıcı tarafından yanlış reddetmeler: Belirsiz istemler, konuşma sentezi sınıflandırıcısında başarısız olabilir. Bu durumda istek reddedilir (PROHIBITED_CONTENT) veya model, stil talimatlarınızı yüksek sesle okur. Bunu önlemek için istemin başında net bir giriş (ör. Audio Profile ve Director's Notes) içeren yapılandırılmış bir istem kullanın.



Desteklenen sesler ve diller

Gemini TTS modelleri, metin girişini alır ve ses çıkışı oluşturur. Bu nedenle yanıt, sentezlenmiş konuşmanın kendisidir. Aşağıdaki alt bölümlerde, Gemini TTS modellerinin "konuşabileceği" (veya yanıt verebileceği) desteklenen sesler ve diller listelenmiştir.

Sesler çok dillidir. Bu nedenle, desteklenen dillerden herhangi birinde konuşma oluşturmak için aynı sesi kullanabilirsiniz. Örneğin, sesi Kore olarak ayarlayabilir ve İspanyolca, Hintçe ve Vietnamca dillerinde bir dizi metin istemi gönderebilirsiniz. Yanıtlar Kore sesinde olacak ancak farklı dillerde verilecek.

Ses adları

Gemini TTS modelleri, her biri farklı özelliklere sahip 30 farklı sentezlenmiş HD ses destekler. Aşağıdaki bölümü genişleterek yanıt sesi seçeneklerinin listesini görüntüleyebilir ve her sesin demosunu dinleyebilirsiniz.

Diller

Gemini TTS modelleri, metin isteminizdeki aşağıdaki dilleri otomatik olarak algılayabilir. Oluşturulan konuşma bu dilde olur.

Konuşma yapılandırmanızda açıkça bir dil kodu ayarlayabileceğinizi unutmayın.

Tüm ses üretme modelleri tarafından desteklenen diller
Dil BCP-47 kodu Dil BCP-47 kodu
Arapça (Mısır) ar-EG Almanca (Almanya) de-DE
İngilizce (ABD) tr-TR İspanyolca (ABD) es-US
Fransızca (Fransa) fr-FR Hintçe (Hindistan) hi-IN
Endonezce (Endonezya) id-ID İtalyanca (İtalya) it-IT
Japonca (Japonya) ja-JP Korece (Kore) ko-KR
Portekizce (Brezilya) pt-BR Rusça (Rusya) ru-RU
Felemenkçe (Hollanda) nl-NL Lehçe (Polonya) pl-PL
Tayca (Tayland) th-TH Türkçe (Türkiye) tr-TR
Vietnamca (Vietnam) vi-VN Rumence (Romanya) ro-RO
Ukraynaca (Ukrayna) uk-UA Bengalce (Bangladeş) bn-BD
İngilizce (Hindistan) en-IN ve hi-IN paketi Marathi dili (Hindistan) mr-IN
Tamilce (Hindistan) ta-IN Telugu dili (Hindistan) te-IN
Ses üreten 3.x modelleri tarafından desteklenen ek diller
Dil BCP-47 kodu Dil BCP-47 kodu
Afrikaanca af Filipince fil
Arnavutça sq Fince fi
Amharca öö Galiçyaca gl
Ermenice hy Gürcüce ka
Azerice az Yunanca el
Baskça eu Gujarati gu
Belarusça be Haiti Creole dili ht
Bulgarca bg İbranice o
Burmaca benim Macarca hu
Katalanca ca İzlandaca :
Sabuanca ceb Cava dili jv
Çince, Mandarin cmn Kannada kn
Hırvatça s Konkani kok
Çek dili cs Laoca lo
Danca da Latince la
Estonca et Letonca lv
Litvanca lt Luxembourgish lb
Makedonca mk Maithili dili mai
Malgaşça mg Malayca ms
Malayalam ml Moğolca mn
Nepalce ne Norveççe, Bokmål nb
Norveççe, Nynorsk nn Oriya veya
Peştuca ps Farsça fa
Punjabi pa Sırpça sr
Sindice sd Seylanca si
Slovakça sk Slovence sl
Swahili sw İsveççe sv
Urduca ur

(İsteğe bağlı) Dil kodunu açıkça ayarlama

Konuşma yapılandırmanızda bir dil kodu belirtmezseniz model, metin isteminizdeki dili otomatik olarak algılar.

Ancak, dili isteğe bağlı olarak açıkça ayarlayabilirsiniz (konuşma yapılandırmasında languageCode parametresini kullanarak). Bunu yapmak için aşağıdaki desteklenen BCP-47 yerel ayar kodlarından birini kullanmanız gerekir:

  • Arapça: ar-XA
  • Bengalce: bn-IN
  • Çince (Mandarin): cmn-CN
  • Felemenkçe: nl-NL
  • İngilizce: en-US, en-GB, en-AU, en-IN
  • Fransızca: fr-FR, fr-CA
  • Almanca: de-DE
  • Gucaratça: gu-IN
  • Hintçe: hi-IN
  • Endonezce: id-ID
  • İtalyanca: it-IT
  • Japonca: ja-JP
  • Kannada: kn-IN
  • Korece: ko-KR
  • Malayalam: ml-IN
  • Marathi: mr-IN
  • Lehçe: pl-PL
  • Portekizce: pt-BR
  • Rusça: ru-RU
  • İspanyolca: es-US, es-ES
  • Tamilce: ta-IN
  • Telugu dili: te-IN
  • Tayca: th-TH
  • Türkçe: tr-TR
  • Vietnamca: vi-VN



Başka ne yapabilirsin?

Diğer özellikleri deneyin

İçerik oluşturmayı kontrol etme hakkında bilgi

Ayrıca istemler ve model yapılandırmalarıyla denemeler yapabilir, hatta Google AI Studio kullanarak oluşturulmuş bir kod snippet'i alabilirsiniz.

Desteklenen modeller hakkında daha fazla bilgi

Çeşitli kullanım alanları için kullanılabilen modeller, bu modellerin kotaları ve fiyatlandırması hakkında bilgi edinin.


Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirim verme