Gemini TTS 모델(gemini-3.8-flash-tts 또는 gemini-3.8-flash-lite-tts)을 사용하여 텍스트에서 자연스럽고 표현력이 풍부한 음성(오디오)을 합성할 수 있습니다. Firebase AI Logic를 사용하면 모바일 또는 웹 앱(예: Apple(Swift), Android(Kotlin/Java), 웹(JavaScript), Flutter(Dart) 또는 Unity 앱)에서 직접 이 요청을 수행할 수 있습니다.
텍스트 음성 변환(TTS) 생성은 제어 가능합니다. 즉, 구조화된 메타데이터와 인라인 음성 태그를 사용하여 감정, 속도, 화자 음성, 웃음이나 한숨과 같은 비음성 소리 등 전달 방식을 안내하면서 정확한 텍스트를 제공하여 음성으로 합성할 수 있습니다. TTS는 스크립트 작성(음성 텍스트 변환)의 반대라고 생각하면 됩니다.
이 기능을 사용하면 다음과 같은 기능을 빌드할 수 있습니다.
- 대화형 스토리텔링 및 오디오북: 긴 형식의 스토리나 캐릭터가 목소리를 바꾸고, 서로 겹치는 백채널로 반응하고, 감정 전달을 조정하는(예: 긴장감 속에서 속삭이거나 농담에 웃는 등) 롤플레잉 게임을 내레이션합니다.
- 지연 시간이 짧은 음성 에이전트 및 어시스턴트: LLM에서 텍스트가 도착하는 즉시 합성된 음성을 스트리밍하여 대화 차례 전반에서 일관된 음성 페르소나를 유지합니다.
- 다국어 콘텐츠 리더 및 언어 튜터: 130개 이상의 언어와 지역별 억양으로 기사, 레시피, 학습 자료를 소리 내어 읽거나 한 대화 내에서 언어를 원활하게 전환할 수 있습니다.
이 가이드에서는 단일 화자 및 다중 화자 음성을 생성하고, 오디오 응답을 스트리밍하고, SpeechMetadata 및 인라인 태그를 사용하여 음성 전달을 지시하고, 사전 빌드된 음성, 라이브러리 음성 또는 커스텀 음성 중에서 선택하는 방법을 보여줍니다.
단일 화자 코드로 바로 이동 다중 화자 코드로 바로 이동 스트리밍 코드로 바로 이동
TTS와 Live API 비교
텍스트 음성 변환(TTS) 모델과 Live API 모델은 모두 지연 시간이 짧은 음성 생성 모델로, 다양한 응답 음성과 언어로 구성할 수 있습니다. 하지만 사용 사례는 매우 다릅니다.
텍스트 음성 변환(TTS) 생성은 단방향 요청-응답 상호작용(텍스트 입력, 오디오 출력)입니다. 팟캐스트 내레이션, 오디오북, 기사 소리 내어 읽기 등 스타일과 사운드를 세밀하게 제어하여 제공된 텍스트를 정확하게 낭독해야 하는 시나리오에 맞게 조정되었습니다.
Live API 세대는 실시간 음성 대화(음성 입력, 음성 출력)를 위한 양방향 스트리밍을 지원합니다. 모델이 반환할 적절한 음성을 결정하는 동적 대화 컨텍스트에서 뛰어난 성능을 발휘합니다. 최신 Live API 모델은 동영상 및 이미지 입력도 지원합니다.
시작하기 전에
|
Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다. |
아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, GenerativeModel 인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.
프롬프트를 테스트하고 반복하려면 Google AI Studio를 사용하는 것이 좋습니다.
이 기능을 지원하는 모델
gemini-3.8-flash-ttsgemini-3.8-flash-lite-tts
TTS 모델 비교
두 Gemini 3.x TTS 모델 모두 요청 스키마와 프롬프트 형식이 동일합니다. 하지만 각 모델을 사용할 때의 차이점은 다음과 같습니다.
| 기능 또는 워크로드 | gemini-3.8-flash-tts |
gemini-3.8-flash-lite-tts |
|---|---|---|
| 주요 강점 | 스튜디오급 음성 충실도, 연기 뉘앙스, 광범위한 방언 지원 | 높은 처리량, 짧은 지연 시간, 비용 효율성 |
| 최적의 사용 사례 | 오디오북, 스튜디오 내레이션, 복잡한 다중 화자 대화, 빈번한 음성 버스트 태그, 어려운 발음, 지역 방언 | 대량 프로덕션, 실시간 음성 에이전트 캐스케이드, 소리 내어 읽어주기 UI 기능, 일상적인 단일 화자 음성 |
| 지원되는 언어 | 132개 언어 | 103개 언어 |
텍스트에서 음성 생성
텍스트 입력에서 단일 화자 음성 또는 두 화자 대화로 음성을 생성할 수 있으며, 전체 WAV 파일(generateContent) 또는 지연 시간이 짧은 원시 PCM 오디오 스트림(generateContentStream)으로 생성할 수 있습니다.
단일 화자의 음성 생성
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다. |
단일 화자 오디오를 생성하는 방법은 다음과 같습니다.
GenerationConfig에서responseModalities를AUDIO로 설정하고 다음을 사용하여SpeechConfig를 구성합니다.(필수) 음성 이름 또는 ID입니다.
Kore와 같은 사전 빌드된 음성, 확장 음성 라이브러리 음성 ID 또는 커스텀 음성voice_.../voicekey_...ID일 수 있습니다.(선택사항) BCP-47 언어 코드입니다. 생략하면 모델이 언어를 자동으로 감지합니다.
다음을 사용하여
TextPart를 만듭니다.(필수) 말할 축어 스크립트입니다.
(선택사항)
style설명이 있는SpeechMetadata(예:"cheerful and friendly")
generateContent를 호출합니다. 기본적으로 단항 요청은 응답의 인라인 데이터 부분에 완전한 WAV(audio/wav) 오디오 파일(16비트 선형 PCM, 24kHz, 모노, 표준 44바이트 RIFF 헤더 포함)을 반환합니다.
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.8-flash-tts",
generationConfig: config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
let prompt = TextPart(
"Have a wonderful day!",
speechMetadata: SpeechMetadata(style: "cheerful and friendly")
)
// Call `generateContent` to generate the speech output.
let response = try await model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let wavData = part.data // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
let mimeType = part.mimeType // for example: "audio/wav"
print("Received audio data with MIME type: \(mimeType)")
// Play the WAV audio data using your own playback helper (for example, with `AVAudioPlayer(data: wavData)`).
playAudio(data: wavData)
}
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.
// Create a `GenerativeModel` instance with a model that supports speech generation.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel(
modelName = "gemini-3.8-flash-tts",
generationConfig = config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
val prompt = content {
text(
text = "Have a wonderful day!",
speechMetadata = SpeechMetadata(style = "cheerful and friendly")
)
}
// Call `generateContent` to generate the speech output.
val response = model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val wavData = part.inlineData // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData)
}
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"), "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.8-flash-tts", config);
// Use the GenerativeModelFutures Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
Content content = new Content.Builder()
.addText("Have a wonderful day!", new SpeechMetadata(null, "cheerful and friendly"))
.build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the speech output.
// Extract the WAV 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[] wavData = ((InlineDataPart) part).getInlineData(); // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData);
}
}
@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.8-flash-tts",
generationConfig
});
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
const prompt = [
{
type: "text",
text: "Have a wonderful day!",
speechMetadata: { style: "cheerful and friendly" }
}
];
// Call `generateContent` to generate the speech output.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the WAV audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const wavBase64 = inlineDataParts[0].inlineData.data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Decode base64 to ArrayBuffer
const wavBuffer = Uint8Array.from(atob(wavBase64), c => c.charCodeAt(0)).buffer;
// The response is a complete WAV file, so the Web Audio API can decode and play it directly.
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(wavBuffer);
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start();
}
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.8-flash-tts',
generationConfig: config,
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
final prompt = Content.multi([
TextPart(
'Have a wonderful day!',
speechMetadata: SpeechMetadata(style: 'cheerful and friendly'),
),
]);
// Call `generateContent` to generate the speech output.
final response = await model.generateContent([prompt]);
// Extract the WAV 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 wavData = part.bytes; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Play the WAV audio data using your preferred audio player or helper (which you'll need to implement).
await playAudio(wavData);
}
Unity
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 language code.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: SpeechConfig.UsePrebuiltVoice("Kore", "en-US")
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.8-flash-tts",
generationConfig: config
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
var prompt = new ModelContent(
new ModelContent.TextPart(
"Have a wonderful day!",
new SpeechMetadata(speaker: null, style: "cheerful and friendly")
)
);
// Call `GenerateContentAsync` to generate the speech output.
var response = await model.GenerateContentAsync(prompt);
// Extract the WAV 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[] wavData = inlineData.Data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
PlayAudio(wavData);
}
}
}
여러 화자가 포함된 음성 생성
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다. |
각 화자에게 고유한 음성을 할당하고 각 대화 줄을 자체 TextPart로 전달하여 단일 요청으로 자연스러운 두 화자 대화를 생성할 수 있습니다.
두 화자 이름(예:
"Joe"및"Jane")을SpeakerVoiceConfig음성에 매핑하는MultiSpeakerVoiceConfig를 만듭니다.GenerationConfig에서responseModalities를AUDIO로 설정하고MultiSpeakerVoiceConfig(및 선택사항인languageCode)를SpeechConfig에 전달합니다.TextPart객체의 배열 또는 목록을 제공합니다. 특히 대화 차례당TextPart하나를 제공합니다. 모든TextPart에서 다음을 사용하여SpeechMetadata를 설정합니다.- (필수)
MultiSpeakerVoiceConfig에 정의된 스피커 이름 중 하나와 일치하는speaker입니다. - (선택사항)
style설명(예:"cheerful and friendly")
- (필수)
generateContent를 호출합니다. 모델은 전체 대화를 합성하고 완전한 WAV(audio/wav) 오디오 파일을 반환합니다.
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.8-flash-tts",
generationConfig: config
)
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
let prompt: [any PartsRepresentable] = [
TextPart(
"How's it going today, Jane?",
speechMetadata: SpeechMetadata(speaker: "Joe", style: "cheerful and friendly")
),
TextPart(
"Not too bad, how about you?",
speechMetadata: SpeechMetadata(speaker: "Jane", style: "calm and relaxed")
)
]
// Call `generateContent` to generate the multi-speaker speech output.
let response = try await model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
for part in response.inlineDataParts {
let wavData = part.data // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
let mimeType = part.mimeType // for example: "audio/wav"
print("Received audio data with MIME type: \(mimeType)")
// Play the WAV audio data using your own playback helper (for example, with `AVAudioPlayer(data: wavData)`).
playAudio(data: wavData)
}
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.8-flash-tts",
generationConfig = config
)
// Provide one text part per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
val prompt = content {
text(
text = "How's it going today, Jane?",
speechMetadata = SpeechMetadata(speaker = "Joe", style = "cheerful and friendly")
)
text(
text = "Not too bad, how about you?",
speechMetadata = SpeechMetadata(speaker = "Jane", style = "calm and relaxed")
)
}
// Call `generateContent` to generate the multi-speaker speech output.
val response = model.generateContent(prompt)
// Extract the WAV audio data and handle it for downstream use. For example:
val part = response.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val wavData = part.inlineData // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData)
}
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, "en-US");
// 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.8-flash-tts", config);
// Use the `GenerativeModelFutures` Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide one text part per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
Content content = new Content.Builder()
.addText(
"How's it going today, Jane?",
new SpeechMetadata("Joe", "cheerful and friendly"))
.addText(
"Not too bad, how about you?",
new SpeechMetadata("Jane", "calm and relaxed"))
.build();
Executor executor = Executors.newSingleThreadExecutor();
// Call `generateContent` to generate the multi-speaker speech output.
// Extract the WAV 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[] wavData = ((InlineDataPart) part).getInlineData(); // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
playAudio(wavData);
}
}
@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.8-flash-tts",
generationConfig
});
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `speechMetadata`.
const prompt = [
{
type: "text",
text: "How's it going today, Jane?",
speechMetadata: { speaker: "Joe", style: "cheerful and friendly" }
},
{
type: "text",
text: "Not too bad, how about you?",
speechMetadata: { speaker: "Jane", style: "calm and relaxed" }
}
];
// Call `generateContent` to generate the multi-speaker speech output.
const result = await model.generateContent(prompt);
const inlineDataParts = result.response.inlineDataParts();
// Extract the WAV audio data and handle it for downstream use. For example:
if (inlineDataParts?.[0]) {
const wavBase64 = inlineDataParts[0].inlineData.data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Decode base64 to ArrayBuffer
const wavBuffer = Uint8Array.from(atob(wavBase64), c => c.charCodeAt(0)).buffer;
// The response is a complete WAV file, so the Web Audio API can decode and play it directly.
const audioCtx = new AudioContext();
const audioBuffer = await audioCtx.decodeAudioData(wavBuffer);
const source = audioCtx.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioCtx.destination);
source.start();
}
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.8-flash-tts',
generationConfig: config,
);
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
final prompt = Content.multi([
TextPart(
"How's it going today, Jane?",
speechMetadata: SpeechMetadata(speaker: 'Joe', style: 'cheerful and friendly'),
),
TextPart(
'Not too bad, how about you?',
speechMetadata: SpeechMetadata(speaker: 'Jane', style: 'calm and relaxed'),
),
]);
// Call `generateContent` to generate the multi-speaker speech output.
final response = await model.generateContent([prompt]);
// Extract the WAV 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 wavData = part.bytes; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Play the WAV audio data using your preferred audio player or helper (which you'll need to implement).
await playAudio(wavData);
}
Unity
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// 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, "en-US");
// Set `responseModalities` to include `Audio`.
var config = new GenerationConfig(
responseModalities: new System.Collections.Generic.List<ResponseModality> { ResponseModality.Audio },
speechConfig: multiSpeechConfig
);
// Create a `GenerativeModel` instance with a model that supports speech generation.
var model = ai.GetGenerativeModel(
modelName: "gemini-3.8-flash-tts",
generationConfig: config
);
// Provide one `TextPart` per dialogue turn, specifying the speaker and optional style in `SpeechMetadata`.
var prompt = new ModelContent(
new ModelContent.TextPart(
"How's it going today, Jane?",
new SpeechMetadata(speaker: "Joe", style: "cheerful and friendly")
),
new ModelContent.TextPart(
"Not too bad, how about you?",
new SpeechMetadata(speaker: "Jane", style: "calm and relaxed")
)
);
// Call `GenerateContentAsync` to generate the multi-speaker speech output.
var response = await model.GenerateContentAsync(prompt);
// Extract the WAV 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[] wavData = inlineData.Data; // WAV audio bytes (24kHz, 1 channel, 16-bit PCM)
// Pass the audio data to your audio player or playback helper (which you'll need to implement).
PlayAudio(wavData);
}
}
}
대답 스트리밍
|
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서 선택한 Gemini API 제공업체의 버튼을 클릭하면 이 페이지에 제공업체별 콘텐츠가 표시됩니다. |
첫 번째 오디오까지의 시간(TTFA)을 줄이고 실시간으로 재생하려면 전체 클립이 완료될 때까지 기다리지 않고 오디오 응답이 생성되는 대로 스트리밍하면 됩니다. 스트리밍은 단일 스피커 및 멀티 스피커 구성 모두에서 작동합니다.
음성을 스트리밍하려면 generateContent 대신 generateContentStream를 호출합니다.
WAV 파일을 반환하는 단항 요청과 달리 스트리밍 요청은 헤더가 없는 원시 16비트 부호 있는 리틀 엔디안 PCM 청크(audio/l16, 24kHz, 모노)를 반환하므로 각 청크를 오디오 출력 버퍼에 직접 추가할 수 있습니다.
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.8-flash-tts",
generationConfig: config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
let prompt = TextPart(
"Tell me a story about a brave knight.",
speechMetadata: SpeechMetadata(style: "warm, engaging audiobook narrator")
)
// Call `generateContentStream` to stream the speech output as it is generated.
let responseStream = try model.generateContentStream(prompt)
// Extract the raw PCM audio chunks and queue them for playback:
for try await chunk in responseStream {
for part in chunk.inlineDataParts {
let pcmChunk = part.data // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
appendAudioChunk(pcmChunk)
}
}
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.8-flash-tts",
generationConfig = config
)
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
val prompt = content {
text(
text = "Tell me a story about a brave knight.",
speechMetadata = SpeechMetadata(style = "warm, engaging audiobook narrator")
)
}
// Call `generateContentStream` to stream the speech output as it is generated.
// Extract the raw PCM audio chunks and queue them for playback.
model.generateContentStream(prompt).collect { chunk ->
val part = chunk.candidates.firstOrNull()?.content?.parts?.firstOrNull()
if (part is InlineDataPart) {
val pcmChunk = part.inlineData // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts", config);
// Use the `GenerativeModelFutures` Java compatibility layer.
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
Content content = new Content.Builder()
.addText(
"Tell me a story about a brave knight.",
new SpeechMetadata(null, "warm, engaging audiobook narrator"))
.build();
// Call `generateContentStream` to stream the speech output as it is generated.
Publisher<GenerateContentResponse> streamingResponse =
model.generateContentStream(content);
// Extract the raw PCM audio chunks and queue them for playback.
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(); // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts",
generationConfig
});
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
const prompt = [
{
type: "text",
text: "Tell me a story about a brave knight.",
speechMetadata: { style: "warm, engaging audiobook narrator" }
}
];
// Call `generateContentStream` to stream the speech output as it is generated.
const result = await model.generateContentStream(prompt);
// Extract the raw PCM audio chunks and queue them for playback:
const playbackQueue = [];
for await (const chunk of result.stream) {
const inlineDataParts = chunk.inlineDataParts();
if (inlineDataParts?.[0]) {
const pcmBase64 = inlineDataParts[0].inlineData.data; // Headerless 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.
// In a real app, start playing chunks as they arrive (rather than waiting for
// the whole stream to finish) to get the low-latency benefit of streaming.
playbackQueue.push(pcmBuffer);
}
}
// To play back an array of PCM buffers in sequence, pass them to your playback helper (which you'll need to write).
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.8-flash-tts',
generationConfig: config,
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
final prompt = Content.multi([
TextPart(
'Tell me a story about a brave knight.',
speechMetadata: SpeechMetadata(style: 'warm, engaging audiobook narrator'),
),
]);
// Call `generateContentStream` to stream the speech output as it is generated.
final responseStream = model.generateContentStream([prompt]);
// Extract the raw PCM audio chunks and queue them for playback:
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; // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
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.8-flash-tts",
generationConfig: config
);
// Provide the verbatim text to synthesize as speech.
// Optionally provide turn-level style metadata.
var prompt = new ModelContent(
new ModelContent.TextPart(
"Tell me a story about a brave knight.",
new SpeechMetadata(speaker: null, style: "warm, engaging audiobook narrator")
)
);
// Call `GenerateContentStreamAsync` to stream the speech output as it is generated.
var responseStream = model.GenerateContentStreamAsync(prompt);
// Extract the raw PCM audio chunks and queue them for playback:
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; // Headerless raw PCM bytes (24kHz, 1 channel, 16-bit)
// Append the audio chunk to your audio queue/buffer for playback (using a helper you implement).
AppendAudioChunk(pcmChunk);
}
}
메타데이터 및 인라인 태그로 음성 출력 제어
Gemini 3.x TTS 모델은 각 TextPart 내의 text를 소리 내어 읽을 축어 스크립트로 엄격하게 처리합니다. 텍스트 문자열 내에 서술형 안내(예: "Say cheerfully:")를 작성하지 마세요. 모델이 해당 단어를 소리 내어 읽을 수 있습니다.
다음 기법을 사용하여 보컬 연주를 연출할 수 있습니다.
대화 수준 style 및 인라인 음성 태그
SpeechMetadata와 인라인 꺾쇠괄호 태그(<...>) 간의 범위별로 성능 방향을 분할합니다.
| 범위 | 배치 위치 | 제어 대상 | 예 |
|---|---|---|---|
|
발화 수준 (전체 발화에서 지속됨) |
SpeechMetadata.style
|
감정, 페르소나, 어조, 억양, 음조, 전반적인 말하기 속도 |
"cheerful and friendly","whispered, nervous","speaking rapidly","out of breath","sarcastic"
|
|
특정 시점 (문장의 특정 순간으로 현지화됨) |
<...>를 사용하여 TextPart 텍스트에 인라인
|
말이 아닌 인간의 목소리, 숨소리, 일시중지 또는 일시적인 전달 변화 |
"Wait... <short pause> did you hear that? <gasp> Someone's at the door."
|
속도 조절, 일시중지, 음조, 강조
구두점 및 줄임표: 스크립트에 쉼표, 대시(
--), 줄임표(...)를 사용하여 자연스러운 문구와 망설임을 만듭니다.명시적 일시중지 태그: 화자가 일시중지해야 하는 정확한 지점에
<short pause>또는<long pause>를 인라인으로 삽입합니다.Hold on, let me think... <short pause> Alright, I've got it.말하기 속도 및 피치:
SpeechMetadata에서style를 설정하여 발화의 전반적인 속도, 피치 또는 억양을 제어합니다(예:"speaking rapidly and excitedly","speaking slowly"또는"monotone and flat"). 독백 중간에 감정이나 속도가 바뀌면 스크립트를 별도의TextPart발화로 분할하고 각 발화에 자체style를 지정합니다.단어 강조: 스크립트에서 특정 단어를 대문자로 표시하여 강조합니다.
It was a VERY long day <sigh> ... nobody listens anymore.
짧은 음성 및 음성 언어 이외의 소리
소리가 발생해야 하는 정확한 단어 경계에 꺾쇠괄호(<...>)를 사용하여 음성이 아닌 인간의 발성을 인라인으로 삽입합니다. 비음성 음향 효과보다는 사람의 음성을 사용합니다. 다음은 사용할 수 있는 추천 태그입니다.
<argh> |
<exhales> |
<heavy breath> |
<scream> |
<snort> |
<breath> |
<gasp> |
<hiss> |
<short pause> |
<sob> |
<cackle> |
<giggle> |
<laugh> /<laughter> |
<shout> |
<throat-clearing> |
<cheer> |
<groan> |
<long pause> |
<shriek> |
<tsk> |
<chuckle> /<chuckles> |
<growl> |
<moan> |
<sigh> /<sighs> |
<whimper> |
<cough> |
<grr> |
<pant> |
<sneeze> |
<whispers> /<whispering> |
<cry> |
<grunt> |
<pff> /<phew> |
<snicker> |
<yawn> |
맞장구 및 음성 겹침
여러 화자가 참여하는 대화에서는 활성 화자의 스크립트 내에서 청취자의 짧은 반응을 파이프 문자(|reaction|)로 래핑할 수 있습니다. 활성 상태가 아닌 발화자는 별도의 차례를 요구하지 않고 자연스럽게 끼어듭니다.
짧은 청취자 백채널:
- 턴 1(
speaker: "Joe"):"So the launch is Thursday |oh hmm| Are we actually ready?" - 대화의 두 번째 부분(
speaker: "Jane"):"Ready enough |oh really?| The last blocker cleared this morning."
- 턴 1(
중복 음성: 여러 파이프 세그먼트를 사용하여 다음과 같이 동시 음성을 시뮬레이션할 수 있습니다(
gemini-3.8-flash-tts에서 가장 잘 작동).- 턴 1(
speaker: "Joe"):"Let's surprise him on three |ok| ready?" - 대화의 두 번째 부분(
speaker: "Jane"):"one. two. three. |happy| happy |birthday| birthday!"
- 턴 1(
일관성 권장사항
먼저
style없이 테스트한 후 간결한style조정 추가: 대부분의 요청은style필드가 비어 있어도 자연스럽게 들립니다. 차례에 특정 전달 조정이 필요한 경우에만 짧은style문구(예:"casual, friendly"또는"reflective and awe-inspired")를 추가하고 일관된 기준을 원할 때는 차례 간에 동일한 짧은 문자열을 재사용합니다.자연스러운 음성 스크립트 작성: 대화형 축약형과 자연스러운 비유창성(예:
"Oh, uh, yeah I think... hm, that's interesting")을 스크립트 텍스트에 직접 포함합니다.기존
[Audio Profile]블록 및 메타 명령어 방지: 긴 페르소나 단락,[Director's Notes]블록 또는"maintain identical timbre"와 같은 메타 명령어는 음성 드리프트를 증가시킵니다. 대신 확장 음성 라이브러리에서 일치하는 음성을 선택하거나 음성 디자인으로 영구적인 캐릭터 음성을 만드세요.style에서 변경할 수 없는 음성 특성을 재정의하려고 시도하지 마세요:SpeechMetadata.style를 사용하여 음성의 연령, 성별 또는 영구적인 억양을 변경하지 마세요. 대신 이러한 특성을 가진 음성을 선택하거나 설계하세요.
지원되는 음성
Gemini 3.x TTS 모델은 음성을 지정하는 세 가지 방법을 지원합니다.
모든 음성은 다국어입니다. 즉, 동일한 음성을 사용하여 지원되는 언어로 음성을 생성하면서 일관된 화자 ID를 유지할 수 있습니다. 예를 들어 음성을 사전 빌드된 Kore 음성으로 설정하고 스페인어, 힌디어, 베트남어로 프롬프트를 전송하면 응답은 모두 각 언어의 Kore 음성을 사용합니다. 30개의 핵심 사전 빌드 음성은 범용 다국어 음성이지만 확장 음성 라이브러리 음성과 커스텀 음성은 기본 언어 또는 지역 억양에 고정되어 있습니다. 즉, 다른 언어로도 말할 수 있지만 기본 언어로 말할 때 가장 자연스럽게 들립니다.
핵심 사전 빌드 음성
Gemini TTS 모델은 각각 고유한 음성 특성을 가진 30개의 핵심 사전 빌드 음성(예: Kore, Puck, Zephyr, Charon, Fenrir)을 지원합니다. SpeechConfig에 음성 이름을 전달합니다(이 페이지 앞부분의 단일 화자 및 다중 화자 예시 참고).
확장 음성 라이브러리의 사전 설정 음성
확장 음성 라이브러리는 사전 제작된 30개의 음성 외에도 다양한 언어, 지역 억양, 연령대, 캐릭터 페르소나, 사용 사례(예: 오디오북, 고객 지원 에이전트, 뉴스 리더)를 아우르는 2,000개 이상의 선별된 사전 설정 음성을 제공합니다.
앱에서 확장 음성 라이브러리의 음성을 사용하는 방법은 다음과 같습니다.
다음 옵션 중 하나를 사용하여 음성을 탐색하고 미리 듣습니다.
Google AI Studio 또는 Agent Studio를 사용하여 음성
id를 가져옵니다.Voices API
list메서드(type=prebuilt및 선택적search쿼리가 있는ListVoices)를 쿼리하여 음성id를 가져옵니다. 자세한 내용은 Gemini Developer API 문서 또는 Agent Platform Gemini API (formerly Vertex AI) 문서를 참고하세요.
라이브러리 음성의
id문자열을SpeechConfig의 음성 이름으로 전달합니다(이 페이지 앞부분의 단일 화자 예시와 유사).
커스텀 음성: 음성 설계 및 음성 복제
Gemini 3.x TTS 모델은 다음 옵션 중 하나를 사용하여 커스텀 음성도 지원합니다.
음성 디자인(미리보기): 화자의 연령, 음색, 억양, 페르소나에 대한 자연어 설명에서 고유한 커스텀 음성을 생성합니다(참조 오디오가 필요하지 않음). 저장된 음성 ID(
voice_...)를 반환합니다.음성 복제(프리뷰): 참조 녹음과 음성 동의 녹음에서 화자의 음성, 어조, 운율을 복제합니다. 프로젝트에 저장된 음성 ID(
voice_...) 또는 스테이트리스(Stateless) 앱 관리 음성 복제 키(voicekey_...)를 반환합니다.
Firebase AI Logic 앱에서 커스텀 음성 사용
커스텀 음성을 만들고 관리하는 것은 관리 또는 서버 측 작업이므로 Firebase AI Logic 클라이언트 SDK는 음성 관리 엔드포인트(CreateVoice, ListVoices, DeleteVoice)를 직접 노출하지 않습니다.
대신 커스텀 음성을 사용하려면 다음을 수행해야 합니다.
다음 옵션 중 하나를 사용하여 커스텀 음성을 한 번 만듭니다.
Google AI Studio 또는 Agent Studio를 사용하여
voice_<id>또는voicekey_<id>식별자를 가져옵니다.Voices API를 사용하여
voice_<id>또는voicekey_<id>식별자를 가져옵니다. 선택한 Gemini API 제공업체 문서에서 자세히 알아보세요.
voice_<id>또는voicekey_<id>문자열을SpeechConfig의 음성 이름으로 전달합니다(이 페이지 앞부분의 단일 화자 예시와 유사).
커스텀 음성을 사용할 때는 다음 요구사항에 유의하세요.
위치(Agent Platform Gemini API (formerly Vertex AI)): 커스텀 음성(
voice_...및voicekey_...)은global위치(Firebase AI Logic를 사용할 때의 기본 위치)에서만 지원됩니다.단일 화자 요청:
MultiSpeakerVoiceConfig는 핵심 사전 빌드 음성만 지원합니다. 여러 캐릭터가 등장하는 대화에서 맞춤 설계되거나 복제된 음성을 사용하려면 각 캐릭터의 대사를 별도의 단일 화자 요청으로 합성하세요.보관 및 만료: 저장된 커스텀 음성(
voice_...)은 1년 동안 사용하지 않으면 만료됩니다(각 합성 요청은 1년 보관 타이머를 재설정함). 스테이트리스(Stateless) 음성 복제 키(voicekey_...)는 생성 후 7일이 지나면 만료됩니다.
지원 언어
Gemini 3.x TTS 모델은 여러 화자가 참여하는 대화에서 프롬프트가 차례마다 언어를 전환하는 경우를 포함하여 입력 텍스트에서 언어를 자동으로 감지합니다.
- Gemini 3.8 Flash TTS(
gemini-3.8-flash-tts): 132개 언어를 지원합니다. - Gemini 3.8 Flash‑Lite TTS(
gemini-3.8-flash-lite-tts): 103개 언어를 지원합니다.
(선택사항) 명시적으로 언어 코드 설정
음성 합성을 특정 언어로 명시적으로 제한하려면 SpeechConfig에 BCP-47 languageCode를 전달하면 됩니다.
오디오 출력 형식
InlineDataPart에서 반환되는 기본 오디오 형식은 단항 요청을 하는지 스트리밍 요청을 하는지에 따라 다릅니다.
| 요청 메소드 | 기본 반환 MIME 유형 | 오디오 형식 세부정보 |
|---|---|---|
|
단항 ( generateContent)
|
audio/wav
|
표준 44바이트 RIFF 헤더가 있는 완전한 WAV 파일(16비트 선형 PCM, 24kHz, 모노, 리틀 엔디안)입니다.
표준 플랫폼 오디오 플레이어(예: Apple 플랫폼의 |
|
스트리밍 ( generateContentStream)
|
audio/l16
|
24kHz, 모노의 헤더 없는 원시 16비트 부호 있는 리틀 엔디안 PCM 청크
청크별 파일 헤더 없이 지연 시간이 짧은 버퍼 큐 및 연결을 위해 설계되었습니다. |
제한사항 및 요구사항
Gemini 3.x TTS 모델을 사용할 때는 다음 제한사항 및 요구사항에 유의하세요.
텍스트 전용 입력, 오디오 전용 출력: TTS 모델은 텍스트 입력(
TextPart)만 허용하며responseModalities를AUDIO로 설정해야 합니다.축어적 합성만: 모델은 제공된 스크립트를 축어적으로 낭독하며 대화형 텍스트 대답을 생성하지 않습니다.
토큰 한도: 요청당 최대 입력은 8,192개 토큰이고 최대 출력은 16,384개 토큰입니다.
다중 화자 제한:
MultiSpeakerVoiceConfig에는 화자 2명이 필요하며 핵심 사전 빌드 음성만 지원합니다. 멀티 스피커 요청의 모든TextPart에는 구성된 스피커 중 하나와 일치하는SpeechMetadata.speaker가 포함되어야 합니다.지원되지 않는 매개변수 및 메서드:
- Firebase AI Logic SDK는 기본 오디오 출력 형식을 재정의하기 위해
GenerationConfig에서responseFormat를 설정하는 것을 아직 지원하지 않습니다. systemInstruction,temperature,topP,topK,candidateCount,presencePenalty또는frequencyPenalty설정은 지원되지 않으며 요청이400 INVALID_ARGUMENT오류와 함께 실패합니다.- TTS 모델에는
countTokens호출이 지원되지 않습니다(토큰 수는 응답의usageMetadata에 반환됨).
- Firebase AI Logic SDK는 기본 오디오 출력 형식을 재정의하기 위해
위치(Agent Platform Gemini API (formerly Vertex AI)): 커스텀 음성(
voice_...및voicekey_...)에는global위치가 필요합니다(Firebase AI Logic를 사용할 때 기본 위치).
gemini-3.1-flash-tts-preview에서 이전
gemini-3.8-flash-tts 및 gemini-3.8-flash-lite-tts 모두 동일한 요청 구조를 사용합니다. 모델 비교 표를 검토하여 워크로드에 가장 적합한 대체 모델을 선택하고 다음과 같이 코드를 업데이트합니다.
| 영역 |
gemini-3.1-flash-tts-preview(기존)
|
gemini-3.8-flash-tts 및gemini-3.8-flash-lite-tts
|
|---|---|---|
| 전달 스타일 및 방향 |
프롬프트 텍스트에 삽입됩니다. 예를 들면 다음과 같습니다."Say cheerfully: ...",[Audio Profile],[Director's Notes]
|
각 TextPart의 SpeechMetadata(style: "...")에 전달됨
|
| 다중 화자 대화 |
인라인 "Speaker: ..." 프리픽스가 있는 단일 텍스트 문자열
|
대화 차례당 TextPart 1개, 각 TextPart에 SpeechMetadata(speaker: "...", style: "...")
|
| 인라인 보컬 태그 |
대괄호 예를 들면 [sigh] 또는 [laughs]입니다.
|
꺾쇠괄호 예를 들면 <sigh> 또는
<laugh> 또는
<short pause>입니다.
|
기본 단항 오디오 형식(generateContent)
|
헤더 없는 원시 16비트 PCM(audio/pcm, 24kHz, 모노)
|
전체 WAV 파일(audio/wav, 16비트 PCM, 24kHz, 모노, 44바이트 RIFF 헤더 포함)
스트리밍( |
| 시스템 요청 사항, 온도, top-P, top-K | 무시됨 |
400 INVALID_ARGUMENT 오류로 거부됩니다. 모델 구성에서 이러한 매개변수를 삭제합니다.
|
마이그레이션 체크리스트
Firebase AI Logic SDK의 최신 버전으로 업그레이드하고 모델 이름을
gemini-3.8-flash-tts또는gemini-3.8-flash-lite-tts로 업데이트합니다.스타일 지침을
SpeechMetadata.style로 이동: 모델이 소리 내어 읽지 않도록 프롬프트 문자열에서"Say cheerfully:"프리픽스,[Audio Profile],[Scene],[Director's Notes]블록을 삭제합니다. 대신SpeechMetadata.style에 간결한 스타일 설명을 전달합니다.여러 화자 스크립트를 별도의
TextPart차례로 분할:"Joe: ... \n Jane: ..."텍스트 블록을 각 차례가SpeechMetadata.speaker를 설정하는TextPart객체의 배열/목록으로 바꿉니다.[...]태그를<...>태그로 변환: 대괄호 오디오 태그(예:[whispers],[sighs],[laughs])를 꺾쇠괄호 보컬 태그(예:<whispers>,<sigh>,<laugh>,<short pause>)로 바꿉니다.단항 오디오 재생 업데이트: 이제
generateContent가 헤더가 없는 원시 PCM 대신 완전한 WAV 파일(44바이트 RIFF 헤더 포함)을 반환하므로 단항 응답에 WAV 헤더를 수동으로 추가하는 코드를 삭제합니다(또는 원시 PCM 샘플을 Android의AudioTrack또는 Unity의AudioClip와 같은 하위 수준 버퍼 API에 제공하는 경우 44바이트 헤더를 건너뜁니다).지원되지 않는 구성 매개변수 삭제: TTS
GenerativeModel구성에서temperature,topP,topK,candidateCount,presencePenalty,frequencyPenalty,systemInstruction를 삭제합니다.
또 뭘 할 수 있니?
-
프로덕션 준비에 대해 생각해 보세요(프로덕션 체크리스트 참조).
- 가능한 한 빨리 Firebase App Check를 시행하여 승인되지 않은 클라이언트의 악용으로부터 Gemini API를 보호하세요.
- Firebase Remote Config 또는 서버 프롬프트 템플릿을 사용하면 앱의 새 버전을 출시하지 않고도 AI 기능의 구성(예: 모델 이름)을 주문형으로 변경할 수 있습니다.
다른 기능 사용해 보기
- 멀티턴 대화(채팅)를 빌드합니다.
- 텍스트 전용 프롬프트에서 텍스트를 생성합니다.
- 텍스트 및 멀티모달 프롬프트에서 구조화된 출력(예: JSON)을 생성합니다.
- 텍스트 및 멀티모달 프롬프트에서 이미지를 생성하고 수정합니다.
- Gemini Live API를 사용하여 입력 및 출력 스트리밍(오디오 포함)
-
도구(예: 함수 호출 및
Google Search 또는Google Maps 를 사용한 그라운딩)를 사용하여 Gemini 모델을 앱의 다른 부분과 외부 시스템 및 정보에 연결합니다.
콘텐츠 생성을 제어하는 방법 알아보기
- 권장사항, 전략, 프롬프트 예시를 포함한 프롬프트 설계 이해
- 최대 출력 토큰, 반복되는 출력 토큰의 확률 등 모델 파라미터를 구성합니다.
- 안전 설정을 사용하여 유해한 것으로 간주될 수 있는 대답을 받을 가능성을 조정합니다.
지원되는 모델 자세히 알아보기
다양한 사용 사례에 사용할 수 있는 모델과 할당량 및 가격 책정에 대해 알아보세요.Firebase AI Logic 사용 경험에 관한 의견 보내기