您可以要求 Gemini 模型分析您提供 以内嵌方式(base64 编码)或通过网址提供的音频文件。使用 Firebase AI Logic, 时,您可以直接从应用发出此请求。
借助此功能,您可以执行以下操作:
- 描述音频内容、总结音频内容或回答有关音频内容的问题
- 转录音频内容
- 使用时间戳分析音频的特定片段
本指南介绍如何根据音频输入生成文本。
|
如需了解使用音频的其他选项,请参阅其他指南 生成结构化输出 多轮对话 双向流式传输 |
准备工作
|
点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容 和代码。 |
如果尚未完成,请完成
入门指南,其中介绍了如何
设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、
为所选的 Gemini API 提供方初始化后端服务,以及
创建 GenerativeModel 实例。
如需测试和迭代提示,我们建议使用 Google AI Studio。
支持此功能的模型
本指南介绍如何根据音频输入生成文本,适用于以下 Gemini模型:
gemini-3.1-pro-previewgemini-3.5-flashgemini-3.1-flash-litegemini-2.5-progemini-2.5-flashgemini-2.5-flash-lite
根据音频文件(base64 编码)生成文本
|
在尝试此示例之前,请完成本指南的
准备工作部分,
以设置您的项目和应用。 在该部分中,您还需要点击所选 Gemini API提供商的按钮,以便在此页面上看到特定于提供商的内容 。 |
您可以要求 Gemini 模型通过文本和音频提示生成文本,方法是提供输入文件的 mimeType 和文件本身。如需了解输入文件的
要求和建议
,请参阅本页面的后续内容。
Swift
您可以调用
generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case.
let model = ai.generativeModel(modelName: "gemini-3.5-flash")
// Provide the audio as `Data`
guard let audioData = try? Data(contentsOf: audioURL) else {
print("Error loading audio data.")
return // Or handle the error appropriately
}
// Specify the appropriate audio MIME type
let audio = InlineDataPart(data: audioData, mimeType: "audio/mpeg")
// Provide a text prompt to include with the audio
let prompt = "Transcribe what's said in this audio recording."
// To generate text output, call `generateContent` with the audio and text prompt
let response = try await model.generateContent(audio, prompt)
// Print the generated text, handling the case where it might be nil
print(response.text ?? "No text in response.")
Kotlin
您可以调用
generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI())
.generativeModel("gemini-3.5-flash")
val contentResolver = applicationContext.contentResolver
val inputStream = contentResolver.openInputStream(audioUri)
if (inputStream != null) { // Check if the audio loaded successfully
inputStream.use { stream ->
val bytes = stream.readBytes()
// Provide a prompt that includes the audio specified above and text
val prompt = content {
inlineData(bytes, "audio/mpeg") // Specify the appropriate audio MIME type
text("Transcribe what's said in this audio recording.")
}
// To generate text output, call `generateContent` with the prompt
val response = model.generateContent(prompt)
// Log the generated text, handling the case where it might be null
Log.d(TAG, response.text?: "")
}
} else {
Log.e(TAG, "Error getting input stream for audio.")
// Handle the error appropriately
}
Java
您可以调用
generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
ListenableFuture。
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("gemini-3.5-flash");
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(audioUri)) {
File audioFile = new File(new URI(audioUri.toString()));
int audioSize = (int) audioFile.length();
byte audioBytes = new byte[audioSize];
if (stream != null) {
stream.read(audioBytes, 0, audioBytes.length);
stream.close();
// Provide a prompt that includes the audio specified above and text
Content prompt = new Content.Builder()
.addInlineData(audioBytes, "audio/mpeg") // Specify the appropriate audio MIME type
.addText("Transcribe what's said in this audio recording.")
.build();
// To generate text output, call `generateContent` with the prompt
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
String text = result.getText();
Log.d(TAG, (text == null) ? "" : text);
}
@Override
public void onFailure(Throwable t) {
Log.e(TAG, "Failed to generate a response", t);
}
}, executor);
} else {
Log.e(TAG, "Error getting input stream for file.");
// Handle the error appropriately
}
} catch (IOException e) {
Log.e(TAG, "Failed to read the audio file", e);
} catch (URISyntaxException e) {
Log.e(TAG, "Invalid audio file", e);
}
Web
您可以调用
generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(ai, { model: "gemini-3.5-flash" });
// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
const base64EncodedDataPromise = new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result.split(','));
reader.readAsDataURL(file);
});
return {
inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
};
}
async function run() {
// Provide a text prompt to include with the audio
const prompt = "Transcribe what's said in this audio recording.";
// Prepare audio for input
const fileInputEl = document.querySelector("input[type=file]");
const audioPart = await fileToGenerativePart(fileInputEl.files);
// To generate text output, call `generateContent` with the text and audio
const result = await model.generateContent([prompt, audioPart]);
// Log the generated text, handling the case where it might be undefined
console.log(result.response.text() ?? "No text in response.");
}
run();
Dart
您可以调用
generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
final model =
FirebaseAI.googleAI().generativeModel(model: 'gemini-3.5-flash');
// Provide a text prompt to include with the audio
final prompt = TextPart("Transcribe what's said in this audio recording.");
// Prepare audio for input
final audio = await File('audio0.mp3').readAsBytes();
// Provide the audio as `Data` with the appropriate audio MIME type
final audioPart = InlineDataPart('audio/mpeg', audio);
// To generate text output, call `generateContent` with the text and audio
final response = await model.generateContent([
Content.multi([prompt,audioPart])
]);
// Print the generated text
print(response.text);
Unity
您可以调用
GenerateContentAsync()
,根据文本和单个音频文件的多模态输入生成文本。
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());
// Create a `GenerativeModel` instance with a model that supports your use case.
var model = ai.GetGenerativeModel(modelName: "gemini-3.5-flash");
// Provide a text prompt to include with the audio
var prompt = ModelContent.Text("Transcribe what's said in this audio recording.");
// Provide the audio as `data` with the appropriate audio MIME type
var audio = ModelContent.InlineData("audio/mpeg",
System.IO.File.ReadAllBytes(System.IO.Path.Combine(
UnityEngine.Application.streamingAssetsPath, "audio0.mp3")));
// To generate text output, call `GenerateContentAsync` with the text and audio
var response = await model.GenerateContentAsync(new [] { prompt, audio });
// Print the generated text
UnityEngine.Debug.Log(response.Text ?? "No text in response.");
了解如何选择适合您的应用场景和应用的模型,以及如何选择模型位置(可选)。
流式传输响应
|
在尝试此示例之前,请完成本指南的
准备工作部分,
以设置您的项目和应用。 在该部分中,您还需要点击所选 Gemini API提供商的按钮,以便在此页面上看到特定于提供商的内容 。 |
您可以不等待模型生成完整结果,而是使用流式传输来处理部分结果,从而实现更快的互动。
如需流式传输响应,请调用 generateContentStream。
输入音频文件的要求和建议
请注意,以内嵌数据形式提供的文件在传输过程中会编码为 base64,这会增加请求的大小。如果请求过大,您会收到 HTTP 413 错误。
如需详细了解以下内容,请参阅“支持的输入文件和要求”页面:
- 在请求中提供文件的不同选项 (以内嵌方式提供,或使用文件的网址或 URI)
- 音频文件的要求和最佳实践
支持的音频 MIME 类型
Gemini 多模态模型支持以下音频 MIME 类型:
- AAC -
audio/aac - FLAC -
audio/flac - MP3 -
audio/mp3 - MPA -
audio/m4a - MPEG -
audio/mpeg - MPGA -
audio/mpga - MP4 -
audio/mp4 - OPUS -
audio/opus - PCM -
audio/pcm - WAV -
audio/wav - WEBM -
audio/webm
每个请求的限制
每个请求的文件数量上限:1 个音频文件
你还可以做些什么?
- 了解如何在 计算 token 数 向模型发送长提示之前。
- 设置 Cloud Storage for Firebase ,以便在多模态请求中包含大型文件,并获得 更易于管理的方式来在提示中提供文件。 文件可以包括图片、PDF、视频和音频。
-
开始考虑为正式版做准备(请参阅
正式版核对清单):
- 尽早设置 Firebase App Check Gemini API,以帮助保护其免遭 未经授权的客户端滥用。
- 集成 Firebase Remote Config 以更新应用中的值(例如模型名称),而无需发布新的应用 版本。
试用其他功能
- 构建多轮对话(聊天)。
- 根据 纯文本提示生成文本。
- 根据文本和多模态提示 生成结构化输出(例如 JSON)。
- 根据文本和多模态提示 生成和修改图片。
- 使用 Gemini Live API 流式传输输入和输出(包括音频) 。 Gemini Live API
- 使用工具(例如 函数调用 和 依托 Google 搜索进行接地)将 Gemini 模型连接到应用的其他部分以及外部 系统和信息。
了解如何控制内容生成
您还可以使用 Google AI Studio Google AI Studio试用提示和模型配置,甚至获取 生成的代码段。
详细了解支持的模型
了解适用于各种应用场景的 模型 及其 配额和 价格。提供反馈 有关您的使用体验Firebase AI Logic