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 kullanırken bu isteği doğrudan uygulamanızdan gönderebilirsiniz.

Metin okuma (TTS) oluşturma işlemi kontrol edilebilir. Yani konuşmaya dönüştürülecek metni tam olarak 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 metne dönüştürmenin (sesle yazma) tam 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 anlatıya uyacak şekilde uyarladığı (ör. gerilim anlarında fısıldama veya şakalara gülme) sürükleyici sesli kitaplar ya da rol yapma oyunları oluşturun.

  • Dil öğrenme: Öğrencilerin zor telaffuzları öğrenmesine yardımcı olmak için metinleri belirli bölgesel aksanlarla veya daha yavaş 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 (ör. son dakika haberleri için ciddi bir ton veya adım adım yemek pişirme talimatları için sıcak, sabırlı bir ton) sesli okuyun.

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

Tek konuşmacı için koda gidin Birden fazla konuşmacı için koda gidin Akış yanıtları için koda gidin

Live API ile TTS karşılaştırması

Hem metin okuma (TTS) modelleri hem de Live API modelleri, farklı yanıt sesleri ve diller için yapılandırılabilen, düşük gecikmeli, konuşma üreten modellerdir. Ancak 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 mod, sağlanan metnin tam olarak okunmasını gerektiren ve stil ile ses üzerinde ayrıntılı kontrol imkanı sunan senaryolar (ör. podcast anlatımı, sesli kitaplar veya makalelerin sesli okunması) için tasarlanmıştır.

  • Live API nesli, 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 başarılıdır. En yeni Live API modellerinin video ve resim girişini de desteklediğini unutmayın.

Başlamadan önce

Bu sayfada sağlayıcıya özel içerikleri ve kodları görüntülemek için Gemini API sağlayıcınızı tıklayın.

Henüz yapmadıysanız başlangıç kılavuzundaki adımları tamamlayın. Bu kılavuzda Firebase projenizi nasıl oluşturacağı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ı için arka uç hizmetini nasıl başlatacağınız ve bir GenerativeModel örneği nasıl oluşturacağınız açıklanmaktadır.

İstemlerinizi test etmek ve yinelemek 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 modelini kullanarak sağlanan metinden konuşma oluşturabilirsiniz.

Tek bir 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ıya ait düğmeyi 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 dosyanıza şunları ekleyin:

Yazılı isteminizle generateContent modelini çağırın. Model, yanıt bölümlerinde ham PCM ses verileri 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 için 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 için 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: [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);
    }
  }
}

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ıya ait düğmeyi 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 üretmek istediğinizde kullanışlıdır.

  1. Konuşmacı adlarını (isteminizde kullanacağınız) belirli yanıt sesi adlarıyla (ör. Kore) eşleyen bir MultiSpeakerVoiceConfig oluşturun.

    Çoklu hoparlör yapılandırması tam olarak 2 hoparlörü destekler.

  2. GenerationConfig dosyanıza şunları ekleyin:

    • responseModalities değerini AUDIO içerecek şekilde ayarlayın.

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

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

Yazılı isteminizle generateContent modelini çağırın. Model, yanıt bölümlerinde ham PCM ses verileri 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 için 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 için 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: [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);
    }
  }
}

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

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ıya ait düğmeyi tıklayarak bu sayfada sağlayıcıya özel içerikleri görebilirsiniz.

Ses dosyasının tamamlanmasını beklemek yerine, oluşturulurken sesli yanıtı aktararak daha hızlı etkileşimler ve daha düşük gecikme süresi elde edebilirsiniz.

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

Konuşma yanıtını aktarmak için generateContent yerine generateContentStream yöntemini çağırın ve parçaları geldikçe işleyin. Aşağıdaki örneklerde, tek konuşmacılı bir yanıtın nasıl aktarılacağı 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 için 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 için 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: [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);
    }
}



İ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 açıklanmaktadır. Ayrıntılı bilgi için bu istem kılavuzunu inceleyin.

İ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 (ör. A warm, professional narrator) açıklayın.

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

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

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

  • Transkript: Söylenecek asıl metindir. En iyi performansı elde etmek 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ıldayarak konuşmak
  • [laughs]: Kahkaha eklemek için
  • [giggles]: Kıkırdamalar eklemek için
  • [sighs]: İç çekme eklemek için
  • [gasp]: Nefes alma sesi eklemek için
  • [shouting]: Bağırmak
  • [excited]: Heyecanlı bir şekilde 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ı bir liste yoktur: Desteklenen etiketlerin sabit bir listesi yoktur. Farklı duygu ve ifadelerle (ör. [bored], [sarcastically], hatta [like dracula]) denemeler yaparak çıkışın nasıl değiştiğini görebilirsiniz.

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

Ö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 oluşturma özelliğini kullanırken aşağıdaki sınırlamaları ve şartları göz önünde bulundurun:

  • Çoklu hoparlör yapılandırması 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 üslubu ve bağlamı, konuşmacının profiliyle uyuşmuyorsa (ör. genç bir kız gibi konuşmaya çalışan kalın bir erkek sesi) modelin çıkışı her zaman seçilen konuşmacıyla tam olarak eşleşmeyebilir. İsteminizin bağlamının sesle eşleştiğinden emin olun.
  • Daha uzun çıkışlar: Birkaç dakikadan uzun seslerde konuşma kalitesi ve tutarlılığı değişebilir. Uzun metin istemlerini daha küçük parçalara bölmenizi öneririz.
  • Ara sıra metin jetonları döndürülüyor: Model, ara sıra ses jetonları yerine metin jetonları döndürür. Bu da isteğin 500 hatasıyla başarısız olmasına neden olur. 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ışlıkla reddedilme: Belirsiz istemler, konuşma sentezi sınıflandırıcısının başarısız olmasına neden olabilir. Bu durumda istek reddedilir (PROHIBITED_CONTENT) veya model, stil talimatlarınızı sesli olarak okur. Bunu önlemek için istemin başında net bir ön talimat (Audio Profile ve Director's Notes gibi) içeren yapılandırılmış bir istem kullanın.



Desteklenen sesler ve diller

Gemini TTS modelleri, metin girişi alır ve ses çıkışı üretir. 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 dilli olduğundan, desteklenen dillerden herhangi birinde konuşma oluşturmak için aynı sesi kullanabilirsiniz. Örneğin, sesi Kore olarak ayarlayıp İspanyolca, Hintçe ve Vietnamca metin istemleri gönderebilirsiniz. Yanıtların tümü Kore sesinde ancak farklı dillerde olacaktır.

Ses adları

Gemini TTS modelleri, her biri farklı özelliklere sahip 30 farklı sentezlenmiş HD sesi 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.

İsteğe bağlı olarak konuşma yapılandırmanızda açıkça bir dil kodu ayarlayabileceğinizi unutmayın.

Tüm ses üreten modeller 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 (Güney 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ı) Açıkça bir dil kodu ayarlama

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

Ancak isterseniz dili açıkça ayarlayabilirsiniz (konuşma yapılandırmasındaki languageCode parametresini kullanarak). Bunun 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
  • Guceratça: gu-IN
  • Hintçe: hi-IN
  • Endonezce: id-ID
  • İtalyanca: it-IT
  • Japonca: ja-JP
  • Kannada dili: kn-IN
  • Korece: ko-KR
  • Malayalamca: ml-IN
  • Marathice: mr-IN
  • Lehçe: pl-PL
  • Portekizce: pt-BR
  • Rusça: ru-RU
  • İspanyolca: es-US, es-ES
  • Tamilce: ta-IN
  • Teluguca: te-IN
  • Tayca: th-TH
  • Türkçe: tr-TR
  • Vietnamca: vi-VN



Başka ne yapabilirsin?

Diğer özellikleri deneme

İçerik üretimini nasıl kontrol edeceğinizi öğrenin.

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

Desteklenen modeller hakkında daha fazla bilgi

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


Firebase AI Logic ile ilgili deneyiminiz hakkında geri bildirimde bulunun