音频理解

Gemini 可以分析和理解音频输入,从而实现以下用例:

  • 描述、总结或回答与音频内容相关的问题。
  • 提供音频转写内容。
  • 分析音频的特定片段。

本指南介绍了如何使用 Gemini API 针对音频输入生成文本回答。

准备工作

在调用 Gemini API 之前,请确保您已安装所选的 SDK,并已配置好 Gemini API 密钥,可以使用。

输入音频

您可以通过以下方式向 Gemini 提供音频数据:

上传音频文件

您可以使用 Files API 上传音频文件。如果请求总大小(包括文件、文本提示、系统说明等)超过 20 MB,请始终使用 Files API。

以下代码会上传音频文件,然后在对 generateContent 的调用中使用该文件。

from google import genai

client = genai.Client(api_key="GOOGLE_API_KEY")

myfile = client.files.upload(file="path/to/sample.mp3")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents=["Describe this audio clip", myfile]
)

print(response.text)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });

async function main() {
  const myfile = await ai.files.upload({
    file: "path/to/sample.mp3",
    config: { mimeType: "audio/mp3" },
  });

  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: createUserContent([
      createPartFromUri(myfile.uri, myfile.mimeType),
      "Describe this audio clip",
    ]),
  });
  console.log(response.text);
}

await main();
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
    log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)

model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
    genai.FileData{URI: file.URI},
    genai.Text("Describe this audio clip"))
if err != nil {
    log.Fatal(err)
}

printResponse(resp)
AUDIO_PATH="path/to/sample.mp3"
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO

tmp_header_file=upload-header.tmp

# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "https://generativelanguage.googleapis.com/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
  -D upload-header.tmp \
  -H "X-Goog-Upload-Protocol: resumable" \
  -H "X-Goog-Upload-Command: start" \
  -H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
  -H "Content-Type: application/json" \
  -d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null

upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"

# Upload the actual bytes.
curl "${upload_url}" \
  -H "Content-Length: ${NUM_BYTES}" \
  -H "X-Goog-Upload-Offset: 0" \
  -H "X-Goog-Upload-Command: upload, finalize" \
  --data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json

file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri

# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [{
        "parts":[
          {"text": "Describe this audio clip"},
          {"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
        }]
      }' 2> /dev/null > response.json

cat response.json
echo

jq ".candidates[].content.parts[].text" response.json

如需详细了解如何处理媒体文件,请参阅 Files API

内嵌传递音频数据

您可以将请求中的内嵌音频数据传递给 generateContent,而不是上传音频文件:

from google.genai import types

with open('path/to/small-sample.mp3', 'rb') as f:
    audio_bytes = f.read()

response = client.models.generate_content(
  model='gemini-2.0-flash',
  contents=[
    'Describe this audio clip',
    types.Part.from_bytes(
      data=audio_bytes,
      mime_type='audio/mp3',
    )
  ]
)

print(response.text)
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const base64AudioFile = fs.readFileSync("path/to/small-sample.mp3", {
  encoding: "base64",
});

const contents = [
  { text: "Please summarize the audio." },
  {
    inlineData: {
      mimeType: "audio/mp3",
      data: base64AudioFile,
    },
  },
];

const response = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: contents,
});
console.log(response.text);
// Initialize a Gemini model appropriate for your use case.
model := client.GenerativeModel("gemini-2.0-flash")

bytes, err := os.ReadFile("path/to/small-sample.mp3")
if err != nil {
  log.Fatal(err)
}

prompt := []genai.Part{
  genai.Blob{MIMEType: "audio/mp3", Data: bytes},
  genai.Text("Please summarize the audio."),
}

// Generate content using the prompt.
resp, err := model.GenerateContent(ctx, prompt...)
if err != nil {
  log.Fatal(err)
}

// Handle the response of generated text
for _, c := range resp.Candidates {
  if c.Content != nil {
    fmt.Println(*c.Content)
  }
}

关于内嵌音频数据,请注意以下几点:

  • 请求大小上限为 20 MB,其中包括文本提示、系统说明和内嵌的文件。如果文件大小会导致请求总大小超过 20 MB,请使用 Files API 上传音频文件以在请求中使用。
  • 如果您要多次使用音频选段,则更高效的方式是上传音频文件

获取转写内容

如需获取音频数据的转写内容,只需在提示中提出请求即可:

myfile = client.files.upload(file='path/to/sample.mp3')
prompt = 'Generate a transcript of the speech.'

response = client.models.generate_content(
  model='gemini-2.0-flash',
  contents=[prompt, myfile]
)

print(response.text)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const myfile = await ai.files.upload({
  file: "path/to/sample.mp3",
  config: { mimeType: "audio/mpeg" },
});

const result = await ai.models.generateContent({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Generate a transcript of the speech.",
  ]),
});
console.log("result.text=", result.text);
// Initialize a Gemini model appropriate for your use case.
model := client.GenerativeModel("gemini-2.0-flash")

// Create a prompt using text and the URI reference for the uploaded file.
prompt := []genai.Part{
  genai.FileData{URI: sampleAudio.URI},
  genai.Text("Generate a transcript of the speech."),
}

// Generate content using the prompt.
resp, err := model.GenerateContent(ctx, prompt...)
if err != nil {
  log.Fatal(err)
}

// Handle the response of generated text
for _, c := range resp.Candidates {
  if c.Content != nil {
    fmt.Println(*c.Content)
  }
}

引用时间戳

您可以使用形式为 MM:SS 的时间戳来引用音频文件的特定部分。例如,以下提示会请求转写内容,

  • 从文件开头算起,开始时间为 2 分 30 秒。
  • 从文件开头算起,结束时间为 3 分 29 秒。

# Create a prompt containing timestamps.
prompt = "Provide a transcript of the speech from 02:30 to 03:29."
// Create a prompt containing timestamps.
const prompt = "Provide a transcript of the speech from 02:30 to 03:29."
// Create a prompt containing timestamps.
prompt := []genai.Part{
    genai.FileData{URI: sampleAudio.URI},
    genai.Text("Provide a transcript of the speech from 02:30 to 03:29."),
}

统计词元数

调用 countTokens 方法可获取音频文件中的令牌数量。例如:

response = client.models.count_tokens(
  model='gemini-2.0-flash',
  contents=[myfile]
)

print(response)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
const myfile = await ai.files.upload({
  file: "path/to/sample.mp3",
  config: { mimeType: "audio/mpeg" },
});

const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.0-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);
tokens, err := model.CountTokens(ctx, genai.FileData{URI: sampleAudio.URI})
if err != nil {
    log.Fatal(err)
}
fmt.Printf("File %s is %d tokens", sampleAudio.DisplayName, tokens.TotalTokens)

支持的音频格式

Gemini 支持以下音频格式 MIME 类型:

  • WAV - audio/wav
  • MP3 - audio/mp3
  • AIFF - audio/aiff
  • AAC - audio/aac
  • OGG Vorbis - audio/ogg
  • FLAC - audio/flac

音频的技术详情

  • Gemini 将每秒的音频表示为 32 个令牌;例如,一分钟的音频表示为 1,920 个令牌。
  • Gemini 只能推断对英语语音的回答。
  • Gemini 可以“理解”非语音内容,例如鸟鸣或警笛。
  • 单个问题中音频数据的支持时长上限为 9.5 小时。Gemini 不限制单个问题中的音频文件数量;不过,单个问题中的所有音频文件总时长不得超过 9.5 小时。
  • Gemini 会将音频文件下采样为 16 Kbps 的数据分辨率。
  • 如果音频源包含多个声道,Gemini 会将这些声道合并为一个声道。

后续步骤

本指南介绍了如何根据音频数据生成文本。如需了解详情,请参阅以下资源:

  • 文件提示策略:Gemini API 支持使用文本、图片、音频和视频数据进行提示,也称为多模态提示。
  • 系统指令:借助系统指令,您可以根据自己的特定需求和使用情形来控制模型的行为。
  • 安全指南:生成式 AI 模型有时会生成意想不到的输出,例如不准确、有偏见或令人反感的输出。后处理和人工评估对于限制此类输出造成伤害的风险至关重要。