您可以要求 Gemini 模型分析您以内嵌(base64 编码)或网址形式提供的音频文件。使用 Vertex AI in Firebase 时,您可以直接从应用发出此请求。
借助此功能,您可以执行以下操作:
- 描述、总结或解答有关音频内容的问题
- 转写音频内容
- 使用时间戳分析音频的特定片段
查看其他指南,了解处理音频的其他选项 生成结构化输出 多轮聊天 双向串流 |
准备工作
如果您尚未完成入门指南,请先完成该指南。该指南介绍了如何设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、初始化 Vertex AI 服务以及创建 GenerativeModel
实例。
如需测试和迭代提示,甚至获取生成的代码段,我们建议使用 Vertex AI Studio。
发送音频文件(采用 base64 编码)并接收文本
在尝试此示例之前,请确保您已完成本指南的准备工作部分。
您可以通过提供输入文件的 mimeType
和文件本身,使用文本和音频提示 Gemini 模型生成文本。请参阅本页下文中的输入文件要求和建议。
Swift
您可以调用 generateContent()
,根据文本和单个音频文件的多模态输入生成文本。
import FirebaseVertexAI
// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()
// Create a `GenerativeModel` instance with a model that supports your use case
let model = vertex.generativeModel(modelName: "gemini-2.0-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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
val generativeModel = Firebase.vertexAI.generativeModel("gemini-2.0-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 = generativeModel.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 Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
GenerativeModel gm = FirebaseVertexAI.getInstance()
.generativeModel("gemini-2.0-flash");
GenerativeModelFutures model = GenerativeModelFutures.from(gm);
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 { getVertexAI, getGenerativeModel } from "firebase/vertexai";
// 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 Vertex AI service
const vertexAI = getVertexAI(firebaseApp);
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(vertexAI, { model: "gemini-2.0-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_vertexai/firebase_vertexai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Vertex AI service and create a `GenerativeModel` instance
// Specify a model that supports your use case
final model =
FirebaseVertexAI.instance.generativeModel(model: 'gemini-2.0-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);
逐字逐句给出回答
在尝试此示例之前,请务必先完成本指南的准备工作部分。
您可以通过不等待模型生成的完整结果,而是使用流式处理部分结果,从而实现更快的互动。如需流式传输响应,请调用 generateContentStream
。
输入音频文件的要求和建议
请参阅“Vertex AI Gemini API 支持的输入文件和要求”,详细了解以下内容:
- 在请求中提供文件的不同方法(内嵌或使用文件的网址或 URI)
- 音频文件的要求和最佳实践
支持的音频 MIME 类型
Gemini 多模态模型支持以下音频 MIME 类型:
音频 MIME 类型 | Gemini 2.0 Flash | Gemini 2.0 Flash‑Lite |
---|---|---|
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 |
每个请求的限制
您最多可以在提示请求中包含
您还可以执行以下操作
- 了解如何在向模型发送长提示之前计算令牌数。
- 设置 Cloud Storage for Firebase,以便在多模式请求中添加大型文件,并获得更可控的解决方案,以便在问题中提供文件。 文件可以是图片、PDF、视频和音频。
- 开始考虑为正式版做好准备,包括设置 Firebase App Check,以保护 Gemini API 免遭未经授权的客户端滥用。 此外,请务必查看正式版核对清单。
试用其他功能
- 构建多轮对话(聊天)。
- 根据纯文本提示生成文本。
- 从文本和多模态提示生成结构化输出(例如 JSON)。
- 根据文本提示生成图片。
- 使用函数调用将生成式模型连接到外部系统和信息。
了解如何控制内容生成
- 了解提示设计,包括最佳实践、策略和示例提示。
- 配置模型参数,例如温度和输出 token 数上限(适用于 Gemini)或宽高比和人物生成(适用于 Imagen)。
- 使用安全设置来调整收到可能被视为有害的回答的可能性。
详细了解支持的模型
了解适用于各种用例的模型及其配额和价格。就您使用 Vertex AI in Firebase 的体验提供反馈