Gemini TTS 모델에 텍스트 프롬프트에서 음성 (오디오) 출력을 생성해 달라고 요청할 수 있습니다. Firebase AI Logic를 사용하면 앱에서 직접 이 요청을 할 수 있습니다.
텍스트 음성 변환 (TTS) 생성은 제어 가능합니다. 즉, 음성으로 합성할 정확한 텍스트를 제공합니다. 또한 프롬프트에서 자연어를 사용하여 오디오 출력의 스타일, 억양, 속도, 어조를 안내할 수 있습니다. TTS는 트랜스크립션 (음성 텍스트 변환)의 반대라고 생각하면 됩니다.
이 기능은 고품질의 짧은 지연 시간 음성 생성에 최적화된 Gemini -tts 모델을 사용하여 사용할 수 있습니다.
이 기능을 사용하면 다음과 같은 작업을 할 수 있습니다.
상호작용형 스토리텔링: 모델이 다양한 캐릭터의 음성을 전환하거나 서사에 맞게 어조를 조정 (예: 서스펜스에서 속삭이거나 농담에 웃음)하는 몰입형 오디오북이나 역할극 게임을 만드세요.
언어 학습: 학습자가 어려운 발음을 연습할 수 있도록 특정 지역의 억양으로 텍스트를 읽거나 느린 속도로 읽을 수 있는 발음 가이드를 만드세요.
맥락 인식 콘텐츠 리더: 콘텐츠에 맞는 음성 페르소나와 감정적 어조 (예: 속보에는 심각한 어조, 단계별 요리 안내에는 따뜻하고 인내심 있는 어조)를 사용하여 뉴스 기사, 레시피 또는 블로그 게시물을 소리 내어 읽어 줍니다.
이 가이드에서는 단일 또는 다중 화자를 사용하여 텍스트 입력에서 음성을 생성하고 오디오 응답을 스트리밍하는 방법을 보여줍니다.
단일 스피커용 코드로 이동 다중 스피커용 코드로 이동 스트리밍된 응답용 코드로 이동
TTS와 Live API 비교
텍스트 음성 변환 (TTS) 모델과 Live API 모델은 모두 지연 시간이 짧고 다양한 응답 음성 및 언어로 구성할 수 있는 음성 생성 모델입니다. 하지만 사용 사례는 매우 다릅니다.
텍스트 음성 변환 (TTS) 생성은 단방향 요청-응답 상호작용 (텍스트 입력, 오디오 출력)입니다. 팟캐스트 내레이션, 오디오북, 기사 낭독과 같이 스타일과 사운드를 세밀하게 제어하여 제공된 텍스트를 정확하게 낭독해야 하는 시나리오에 적합합니다.
Live API 생성은 실시간 음성 대화 (음성 입력, 음성 출력)를 위한 양방향 스트리밍을 지원합니다. 모델이 반환할 적절한 음성을 결정하는 동적 대화 컨텍스트에서 뛰어난 성능을 발휘합니다. 최신 Live API 모델은 동영상 및 이미지 입력도 지원합니다.
시작하기 전에
|
Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다. |
아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, GenerativeModel 인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.
프롬프트를 테스트하고 반복하려면 Google AI Studio를 사용하는 것이 좋습니다.
이 기능을 지원하는 모델
gemini-3.1-flash-tts-preview
텍스트에서 음성 생성
Gemini TTS 모델을 사용하여 제공된 텍스트에서 음성을 생성할 수 있습니다.
단일 화자로 음성 생성
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다. |
단일 음성을 사용하여 오디오를 출력하도록 모델을 구성할 수 있습니다.
GenerationConfig에 다음을 포함합니다.
AUDIO을 포함하도록responseModalities을 설정합니다.다음과 같이
SpeechConfig를 구성합니다.(필수) 대답 음성 이름 (예:
Kore)(선택사항) 언어 코드입니다.
언어를 지정하지 않으면 Gemini TTS 모델이 프롬프트에서 언어를 자동으로 감지할 수 있습니다.
텍스트 프롬프트로 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의 스트리밍 메서드는 Reactive Streams 라이브러리에서Publisher 유형을 반환합니다.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore"), "en-US"))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt.
String prompt = "Say cheerfully: Have a wonderful day!";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
Part part = result.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmData = ((InlineDataPart) part).getInlineData();
String mimeType = ((InlineDataPart) part).getMimeType();
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } },
languageCode: "en-US"
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt.
const prompt = "Say cheerfully: Have a wonderful day!";
// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data;
// Decode base64 to ArrayBuffer
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// To play back a PCM buffer, you'll need to write your own `playAudio` function.
playAudio(pcmBuffer);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
responseModalities: [ResponseModality.audio],
speechConfig: SpeechConfig(voiceName: 'Kore', languageCode: 'en-US'),
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
config: config,
);
// Provide a text prompt.
final prompt = 'Say cheerfully: Have a wonderful day!';
// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmData = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
await playAudio(pcmData);
}
Unity
using Firebase.AI;
// Set `responseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name and language code.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore", "en-US")
);
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt.
var prompt = "Say cheerfully: Have a wonderful day!";
// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
foreach (var part in response.Candidates[0].Content.Parts) {
if (part is ModelContent.InlineDataPart inlineData) {
byte[] pcmData = inlineData.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
}
여러 화자가 포함된 음성 생성
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다. |
텍스트의 화자에 따라 다른 음성을 사용하도록 모델을 구성할 수 있습니다. 이는 대화 또는 대화의 오디오를 생성하는 데 유용합니다.
화자 이름 (프롬프트에서 사용)을 특정 대답 음성 이름 (예:
Kore)에 매핑하는MultiSpeakerVoiceConfig을 만듭니다.다중 스피커 구성은 정확히 2개의 스피커를 지원합니다.
GenerationConfig에 다음을 포함합니다.AUDIO을 포함하도록responseModalities을 설정합니다.다음과 같이
SpeechConfig를 구성합니다.(필수)
MultiSpeakerVoiceConfig를 전달합니다.(선택사항) 언어 코드입니다.
언어를 지정하지 않으면 Gemini TTS 모델이 프롬프트에서 언어를 자동으로 감지할 수 있습니다.
프롬프트에서 화자 이름을 접두사로 사용하여 누가 말하는지 나타냅니다 (예:
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 유형을 반환합니다.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
MultiSpeakerVoiceConfig multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
Arrays.asList(
new SpeakerVoiceConfig("Joe", new Voice("Puck")),
new SpeakerVoiceConfig("Jane", new Voice("Kore"))
)
);
SpeechConfig multiSpeechConfig = new SpeechConfig(multiSpeakerVoiceConfig);
// Set `responseModalities` to include `AUDIO`.
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(multiSpeechConfig)
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt that includes the names of the speakers.
String prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
Content content = new Content.Builder().addText(prompt).build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output based on your text prompt.
// Extract the audio data and handle it for downstream use.
ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
Part part = result.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmData = ((InlineDataPart) part).getInlineData(); // Raw PCM bytes (24kHz, 1 channel, 16-bit)
String mimeType = ((InlineDataPart) part).getMimeType(); // for example: "audio/pcm"
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
multiSpeakerVoiceConfig: {
speakerVoiceConfigs: [
{ speaker: "Joe", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Puck" } } },
{ speaker: "Jane", voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } } }
]
},
languageCode: "en-US"
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt that includes the names of the speakers.
const prompt = `
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
`;
// Call `generateContent` to generate the speech output based on your text prompt.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// To play back a PCM buffer, you'll need to write your own `playAudio` function.
playAudio(pcmBuffer);
}
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
final multiSpeechConfig = SpeechConfig.multiSpeaker(
multiSpeakerVoiceConfig: MultiSpeakerVoiceConfig(
speakerVoiceConfigs: [
SpeakerVoiceConfig(speaker: 'Joe', voiceName: 'Puck'),
SpeakerVoiceConfig(speaker: 'Jane', voiceName: 'Kore'),
],
),
languageCode: 'en-US',
);
// Set `responseModalities` to include `audio`.
final config = GenerationConfig(
responseModalities: [ResponseModality.audio],
speechConfig: multiSpeechConfig,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
config: config,
);
// Provide a text prompt that includes the names of the speakers.
final prompt = '''
Joe: How's it going today Jane?
Jane: Not too bad, how about you?
''';
// Call `generateContent` to generate the speech output based on your text prompt.
final response = await model.generateContent([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
final part = response.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmData = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
await playAudio(pcmData);
}
Unity
using Firebase.AI;
// Configure a `SpeechConfig` for multiple speakers, assigning a voice to each speaker.
var multiSpeakerVoiceConfig = new MultiSpeakerVoiceConfig(
new System.Collections.Generic.List<SpeakerVoiceConfig> {
SpeakerVoiceConfig.UsePrebuiltVoice("Joe", "Puck"),
SpeakerVoiceConfig.UsePrebuiltVoice("Jane", "Kore")
}
);
var multiSpeechConfig = SpeechConfig.UseMultiSpeakerVoice(multiSpeakerVoiceConfig);
// Set `responseModalities` to include `Audio`.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: multiSpeechConfig
);
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt that includes the names of the speakers.
var prompt = "Joe: How's it going today Jane?\nJane: Not too bad, how about you?";
// Call `GenerateContentAsync` to generate the speech output based on your text prompt.
var response = await model.GenerateContentAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
if (response.Candidates.Count > 0) {
foreach (var part in response.Candidates[0].Content.Parts) {
if (part is ModelContent.InlineDataPart inlineData) {
byte[] pcmData = inlineData.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// To play back PCM audio data, you'll need to write your own `playAudio` function.
playAudio(pcmData);
}
}
}
대답 스트리밍
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다. |
전체 오디오 파일이 완료될 때까지 기다리는 대신 오디오 응답이 생성되는 대로 스트리밍하면 상호작용 속도를 높이고 지연 시간을 줄일 수 있습니다.
생성된 음성의 스트리밍은 단일 화자 및 다중 화자 구성 모두에서 지원됩니다. Gemini 3.x TTS 모델을 사용하는 경우에만 지원됩니다.
음성 응답을 스트리밍하려면 generateContent 대신 generateContentStream를 호출하고 청크가 도착하면 처리합니다. 다음 예는 단일 스피커 응답을 스트리밍하는 방법을 보여줍니다.
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 유형을 반환합니다.
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
GenerationConfig config = new GenerationConfig.Builder()
.setResponseModalities(Collections.singletonList(ResponseModality.AUDIO))
.setSpeechConfig(new SpeechConfig(new Voice("Kore")))
.build();
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.1-flash-tts-preview", config);
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide a text prompt.
String prompt = "Tell me a story about a brave knight.";
Content content = new Content.Builder().addText(prompt).build();
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(content);
// Extract the audio data and handle it for downstream use.
streamingResponse.subscribe(new Subscriber<GenerateContentResponse>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(GenerateContentResponse chunk) {
Part part = chunk.getCandidates().get(0).getContent().getParts().get(0);
if (part instanceof InlineDataPart) {
byte[] pcmChunk = ((InlineDataPart) part).getInlineData(); // Raw PCM bytes (24kHz, 1 channel, 16-bit)
String mimeType = ((InlineDataPart) part).getMimeType(); // for example: "audio/pcm"
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
@Override
public void onComplete() {
// Audio stream complete.
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
});
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } from "firebase/ai";
// TODO(developer): Replace with your app's Firebase configuration
const firebaseConfig = { /* ... */ };
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Set `responseModalities` to include `AUDIO`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
const generationConfig = {
responseModalities: [ResponseModality.AUDIO],
speechConfig: {
voiceConfig: { prebuiltVoiceConfig: { voiceName: "Kore" } }
}
};
// Create a `GenerativeModel` instance with a model that supports speech generation.
const model = getGenerativeModel(ai, {
model: "gemini-3.1-flash-tts-preview",
generationConfig
});
// Provide a text prompt.
const prompt = "Tell me a story about a brave knight.";
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
const result = await model.generateContentStream(prompt);
// Extract the audio data and handle it for downstream use. For example:
const playbackQueue = [];
for await (const chunk of result.stream) {
const inlineDataParts = chunk.inlineDataParts();
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
const pcmBuffer = Uint8Array.from(atob(pcmBase64), c => c.charCodeAt(0)).buffer;
// Append the audio chunk to your audio queue/buffer for playback.
playbackQueue.push(pcmBuffer);
}
}
// To play back an array of PCM buffers in sequence, you'll need to write your own `processPlaybackQueue` function.
processPlaybackQueue(playbackQueue);
Dart
import 'package:firebase_ai/firebase_ai.dart';
// Set `responseModalities` to include `audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
final config = GenerationConfig(
responseModalities: [ResponseModality.audio],
speechConfig: SpeechConfig(voiceName: 'Kore'),
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports speech generation.
final model = FirebaseAI.googleAI().generativeModel(
model: 'gemini-3.1-flash-tts-preview',
config: config,
);
// Provide a text prompt.
final prompt = 'Tell me a story about a brave knight.';
// Call `generateContentStream` to generate the speech output stream based on your text prompt.
final responseStream = model.generateContentStream([Content.text(prompt)]);
// Extract the audio data and handle it for downstream use. For example:
await for (final chunk in responseStream) {
final part = chunk.candidates.first.content.parts.first;
if (part is InlineDataPart && part.mimeType.startsWith('audio/')) {
final Uint8List pcmChunk = part.bytes; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
Unity
using System.Collections.Generic;
using System.Linq;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Set `ResponseModalities` to include `Audio`.
// Configure a `SpeechConfig` with your chosen voice name (and optionally a language code).
var config = new GenerationConfig(
responseModalities: new List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore")
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.1-flash-tts-preview",
generationConfig: config
);
// Provide a text prompt.
var prompt = "Tell me a story about a brave knight.";
// Call `GenerateContentStreamAsync` to generate the speech output stream based on your text prompt.
var responseStream = model.GenerateContentStreamAsync(prompt);
// Extract the audio data and handle it for downstream use. For example:
await foreach (var response in responseStream)
{
var audioParts = response.Candidates.FirstOrDefault().Content.Parts
.OfType<ModelContent.InlineDataPart>();
foreach (var part in audioParts)
{
byte[] pcmChunk = part.Data; // Raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback.
appendAudioChunk(pcmChunk);
}
}
프롬프트로 음성 출력 제어하기
특정 프롬프트 기법을 사용하여 생성된 음성의 어조, 속도, 스타일에 영향을 줄 수 있습니다.
프롬프트 구조 및 오디오 태그에 관한 다음 하위 섹션에서는 개략적인 가이드라인을 설명합니다. 자세한 안내는 이 프롬프트 가이드를 참고하세요.
프롬프트 구조
최상의 결과를 얻으려면 다음 구성요소를 사용하여 프롬프트를 구성하세요.
Audio Profile: 화자의 페르소나, 핵심 정체성, 원형 (예:A warm, professional narrator)을 설명합니다.Scene: 환경과 감정적 분위기를 설명합니다 (예:In a quiet library또는Amidst a noisy crowd).Director's Notes: 감정, 속도, 스타일, 억양을 설명합니다 (예:Speak slowly and with mystery).Sample Context: 모델에 시작점을 제공합니다 (예:The speaker is greeting a close friend).스크립트: 말할 실제 텍스트입니다. 최상의 성능을 위해 텍스트의 어조와 맥락이 음성 프로필 및 연출 메모와 일치해야 합니다.
프롬프트 예시:
[Audio Profile: A young, energetic voice]
[Scene: A lively sports broadcast]
[Director's Notes: Speak fast, with high energy and excitement]
[Sample Context: The game just ended with a last-second touchdown]
Welcome back fans! What an incredible game we're witnessing today!
오디오 태그
서식 태그를 텍스트 프롬프트에 직접 삽입하여 모델의 성능을 안내할 수 있습니다.
오디오 태그는 Gemini 3.x TTS 모델을 사용할 때만 지원됩니다.
흔히 사용되는 태그는 다음과 같습니다.
[whispers]: 속삭이는 소리로 말하기[laughs]: 웃음 추가[giggles]: 웃음소리 추가[sighs]: 한숨 추가[gasp]: 숨을 들이쉬는 소리를 추가합니다.[shouting]: 외치기[excited]: 신나게 말하기[serious]: 진지하게 말하기[sighs whispers]: 결합된 감정 (태그를 결합할 수 있음)
오디오 태그를 사용할 때는 다음 사항에 유의하세요.
전체 목록 없음: 지원되는 태그의 고정 목록은 없습니다. 다양한 감정과 표현 (예:
[bored],[sarcastically],[like dracula])을 실험하여 출력이 어떻게 변하는지 확인할 수 있습니다.영어가 아닌 텍스트 프롬프트: 텍스트 프롬프트가 영어로 되어 있지 않더라도 최상의 결과를 얻으려면 영어 오디오 태그를 사용해야 합니다.
프롬프트 예시:
I have a secret to tell you. [whispers] I found the hidden treasure. [laughs] I can't believe it!
제한사항 및 요구사항
음성 생성 기능을 사용할 때는 다음 제한사항 및 요구사항에 유의하세요.
다중 스피커 구성은 정확히 2개의 스피커를 지원합니다.
다음 기능은 Gemini 3.x TTS 모델을 사용하는 경우에만 지원됩니다. 스트리밍, 오디오 태그, 추가 자동 감지 언어
gemini-3.1-flash-tts-preview의 제약 조건
- 음성 불일치: 프롬프트의 어조와 맥락이 선택한 스피커의 프로필과 일치하지 않으면 (예: 깊은 남성 음성이 어린 소녀처럼 말하려고 함) 모델의 출력이 선택한 스피커와 항상 엄격하게 일치하지 않을 수 있습니다. 프롬프트 컨텍스트가 음성과 일치해야 합니다.
- 더 긴 출력: 몇 분이 넘는 오디오의 경우 음성 품질과 일관성이 떨어질 수 있습니다. 긴 텍스트 프롬프트를 더 작은 청크로 분할하는 것이 좋습니다.
- 텍스트 토큰이 가끔 반환됨: 모델이 오디오 토큰 대신 텍스트 토큰을 가끔 반환하여
500오류와 함께 요청이 실패합니다. 이 오류는 요청의 일부에서 무작위로 발생하므로 앱에 재시도 로직을 구현해야 합니다. - 분류기의 잘못된 거부: 모호한 프롬프트는 음성 합성 분류기를 통과하지 못하여 요청이 거부(
PROHIBITED_CONTENT)되거나 모델이 스타일 지침을 큰 소리로 읽을 수 있습니다. 이를 방지하려면 프롬프트 시작 부분에 명확한 서문 (예:Audio Profile및Director's Notes)이 있는 구조화된 프롬프트를 사용하세요.
지원되는 음성 및 언어
Gemini TTS 모델은 텍스트 입력을 받아 오디오 출력을 생성하므로 대답은 합성된 음성 자체입니다. 다음 하위 섹션에는 Gemini TTS 모델이 '말할'(또는 대답할) 수 있는 지원되는 음성 및 언어가 나열되어 있습니다.
음성은 다국어이므로 지원되는 언어로 음성을 생성할 때 동일한 음성을 사용할 수 있습니다. 예를 들어 음성을 Kore로 설정하고 스페인어, 힌디어, 베트남어로 된 텍스트 프롬프트를 보낼 수 있습니다. 대답은 모두 Kore 음성으로 제공되지만 언어는 각각 다릅니다.
음성 이름
Gemini TTS 모델은 각각 고유한 특성을 가진 30가지의 합성 HD 음성을 지원합니다. 아래 섹션을 펼쳐 응답 음성 옵션 목록을 확인하고 각 음성의 데모를 들어볼 수 있습니다.
언어
Gemini TTS 모델은 텍스트 프롬프트에서 다음 언어를 자동으로 감지할 수 있습니다. 생성된 음성은 해당 언어로 표시됩니다.
음성 구성에서 언어 코드를 명시적으로 설정할 수도 있습니다.
모든 오디오 생성 모델에서 지원하는 언어
| 언어 | BCP-47 코드 | 언어 | BCP-47 코드 |
|---|---|---|---|
| 아랍어(이집트) | ar-EG | 독일어(독일) | de-DE |
| 영어(미국) | en-US | 스페인어(미국) | es-US |
| 프랑스어(프랑스) | fr-FR | 힌디어(인도) | hi-IN |
| 인도네시아어(인도네시아) | id-ID | 이탈리아어(이탈리아) | it-IT |
| 일본어(일본) | ja-JP | 한국어(대한민국) | ko-KR |
| 포르투갈어(브라질) | pt-BR | 러시아어(러시아) | ru-RU |
| 네덜란드어(네덜란드) | nl-NL | 폴란드어(폴란드) | pl-PL |
| 태국어(태국) | th-TH | 터키어(터키) | tr-TR |
| 베트남어(베트남) | vi-VN | 루마니아어(루마니아) | ro-RO |
| 우크라이나어(우크라이나) | uk-UA | 벵골어(방글라데시) | bn-BD |
| 영어(인도) | en-IN 및 hi-IN 번들 | 마라티어(인도) | mr-IN |
| 타밀어(인도) | ta-IN | 텔루구어(인도) | te-IN |
오디오 생성 3.x 모델에서 지원되는 추가 언어
| 언어 | BCP-47 코드 | 언어 | BCP-47 코드 |
|---|---|---|---|
| 아프리칸스어 | af | 필리핀어 | fil |
| 알바니아어 | sq | 핀란드어 | fi |
| 암하라어 | am | 갈리시아어 | gl |
| 아르메니아어 | hy | 조지아어 | ka |
| 아제르바이잔어 | az | 그리스어 | el |
| 바스크어 | eu | 구자라트어 | gu |
| 벨라루스어 | be | 아이티 크리올어 | ht |
| 불가리아어 | bg | 히브리어 | he |
| 버마어 | my | 헝가리어 | hu |
| 카탈로니아어 | ca | 아이슬란드어 | is |
| 세부아노어 | ceb | 자바어 | jv |
| 중국어, 북경어 | cmn | 칸나다어 | kn |
| 크로아티아어 | 시간 | 콘칸어 | kok |
| 체코어 | cs | 라오어 | lo |
| 덴마크어 | da | 라틴어 | la |
| 에스토니아어 | et | 라트비아어 | lv |
| 리투아니아어 | lt | 룩셈부르크어 | lb |
| 마케도니아어 | mk | 마이틸리어 | mai |
| 마다가스카르어 | mg | 말레이어 | ms |
| 말라얄람어 | ml | 몽골어 | mn |
| 네팔어 | ne | 노르웨이어(보크말) | nb |
| 노르웨이어(뉘노르스크) | nn | 오리야어 | 또는 |
| 파슈토어 | ps | 페르시아어 | fa |
| 펀자브어 | pa | 세르비아어 | sr |
| 신드어 | sd | 신할라어 | si |
| 슬로바키아어 | sk | 슬로베니아어 | sl |
| 스와힐리어 | sw | 스웨덴어 | sv |
| 우르두어 | ur |
(선택사항) 언어 코드 명시적으로 설정
음성 구성에서 언어 코드를 지정하지 않으면 모델이 텍스트 프롬프트의 언어를 자동으로 감지합니다.
하지만 언어를 명시적으로 설정할 수도 있습니다 (음성 구성에서 languageCode 매개변수 사용). 이렇게 하려면 지원되는 다음 BCP-47 언어 코드 중 하나를 사용해야 합니다.
- 아랍어:
ar-XA - 벵골어:
bn-IN - 중국어 (표준어):
cmn-CN - 네덜란드어:
nl-NL - 영어:
en-US,en-GB,en-AU,en-IN - 프랑스어:
fr-FR,fr-CA - 독일어:
de-DE - 구자라트어:
gu-IN - 힌디어:
hi-IN - 인도네시아어:
id-ID - 이탈리아어:
it-IT - 일본어:
ja-JP - 칸나다어:
kn-IN - 한국어:
ko-KR - 말라얄람어:
ml-IN - 마라티어:
mr-IN - 폴란드어:
pl-PL - 포르투갈어:
pt-BR - 러시아어:
ru-RU - 스페인어:
es-US,es-ES - 타밀어:
ta-IN - 텔루구어:
te-IN - 태국어:
th-TH - 튀르키예어:
tr-TR - 베트남어:
vi-VN
또 뭘 할 수 있어?
- 모델에 긴 프롬프트를 전송하기 전에 토큰 수를 집계하는 방법을 알아보세요.
-
프로덕션 준비를 시작합니다 (프로덕션 체크리스트 참고).
- 가능한 한 빨리 Firebase App Check을 적용하여 승인되지 않은 클라이언트의 악용으로부터 Gemini API을 보호하세요.
- Firebase Remote Config 또는 서버 프롬프트 템플릿을 사용하여 앱의 새 버전을 출시하지 않고도 AI 기능의 구성 (예: 모델 이름)을 필요에 따라 변경할 수 있습니다.
다른 기능 사용해 보기
- 멀티턴 대화 (채팅)를 빌드합니다.
- 텍스트 전용 프롬프트에서 텍스트를 생성합니다.
- 텍스트 및 멀티모달 프롬프트에서 구조화된 출력 (예: JSON)을 생성합니다.
- 텍스트 및 멀티모달 프롬프트에서 이미지를 생성하고 편집합니다.
- Gemini Live API를 사용하여 스트림 입력 및 출력 (오디오 포함)
-
Gemini 모델을 앱의 다른 부분과 외부 시스템 및 정보에 연결하려면 도구 (예: 함수 호출 및
Google Search 또는Google Maps 을 사용한 그라운딩)를 사용하세요.
콘텐츠 생성 제어 방법 알아보기
- 권장사항, 전략, 예시 프롬프트를 비롯한 프롬프트 설계 이해하기
- 최대 출력 토큰, 반복된 출력 토큰의 확률 등 모델 파라미터를 구성합니다.
- 안전 설정 사용을 통해 유해하다고 간주될 수 있는 대답을 받을 가능성을 조정합니다.
지원되는 모델 자세히 알아보기
다양한 사용 사례에 사용할 수 있는 모델과 해당 모델의 할당량 및 가격에 대해 알아봅니다.Firebase AI Logic 사용 경험에 관한 의견 보내기