Gemini 中文指南
获取 API 密钥 ↗

音频理解

↓ 下载 Markdown

Gemini 可以分析音频输入并生成文本响应。

python
  from google import genai

  client = genai.Client()

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

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

  print(response.text)

概览 #

Gemini 可以分析和理解音频输入并为其生成文本响应,从而实现如下用例:

  • 描述、总结或回答有关音频内容的问题。
  • 提供音频的转录和翻译(语音到文本)。
  • 检测言语和音乐中的情绪。
  • 分析音频的特定片段并提供时间戳。

截至目前,Gemini API 不支持实时转录用例。有关实时语音和视频交互,请参阅 Live API。对于支持实时转录的专用语音到文本模型,请使用 Google Cloud 语音转文本 API.

将语音转录为文本 #

此示例应用程序展示了如何提示 Gemini API 转录、翻译和总结语音,包括使用时间戳和情绪检测 结构化输出.

python
  from google import genai
  from google.genai import types

  client = genai.Client()

  YOUTUBE_URL = "https://www.youtube.com/watch?v=ku-N-eS1lgM"

  def main():
    prompt = """
      Process the audio file and generate a detailed transcription.

      Requirements:

      1. Provide accurate timestamps for each segment (Format: MM:SS).
      2. Detect the primary language of each segment.
      3. If the segment is in a language different than English, also provide the English translation.
      4. Identify the primary emotion of the speaker in this segment. You MUST choose exactly one of the following: Happy, Sad, Angry, Neutral.
      5. Provide a brief summary of the entire audio at the beginning.
    """

    response = client.models.generate_content(
      model="gemini-4-hydrogen",
      contents=[
        types.Content(
          parts=[
            types.Part(
              file_data=types.FileData(
                file_uri=YOUTUBE_URL
              )
            ),
            types.Part(
              text=prompt
            )
          ]
        )
      ],
      config=types.GenerateContentConfig(
        response_mime_type="application/json",
        response_schema=types.Schema(
          type=types.Type.OBJECT,
          properties={
            "summary": types.Schema(
              type=types.Type.STRING,
              description="A concise summary of the audio content.",
            ),
            "segments": types.Schema(
              type=types.Type.ARRAY,
              description="List of transcribed segments with timestamp.",
              items=types.Schema(
                type=types.Type.OBJECT,
                properties={
                  "timestamp": types.Schema(type=types.Type.STRING),
                  "content": types.Schema(type=types.Type.STRING),
                  "language": types.Schema(type=types.Type.STRING),
                  "language_code": types.Schema(type=types.Type.STRING),
                  "translation": types.Schema(type=types.Type.STRING),
                  "emotion": types.Schema(
                    type=types.Type.STRING,
                    enum=["happy", "sad", "angry", "neutral"]
                  ),
                },
                required=["timestamp", "content", "language", "language_code", "emotion"],
              ),
            ),
          },
          required=["summary", "segments"],
        ),
      ),
    )

    print(response.text)

  if __name__ == "__main__":
    main()

您可以提示 人工智能工作室构建 创建一个应用程序就像 这个示例转录应用程序 ,只需单击一个按钮。

输入音频 #

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

要了解其他文件输入方法,请参阅 文件输入方式 指导。

上传音频文件 #

您可以使用 Files API 上传音频文件。当总请求大小(包括文件、文本提示、系统指令等)大于 20 MB 时,请始终使用 Files API。

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

python
  from google import genai

  client = genai.Client()

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

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

  print(response.text)

要了解有关使用媒体文件的更多信息,请参阅 Files API.

内嵌传递音频数据 #

您可以将请求中的内联音频数据传递给 generateContent:

javascript
  import {
    GoogleGenAI,
    createUserContent,
    createPartFromUri,
  } from "@google/genai";

  const ai = new GoogleGenAI({});

  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-4-hydrogen",
      contents: createUserContent([
        createPartFromUri(myfile.uri, myfile.mimeType),
        "Describe this audio clip",
      ]),
    });
    console.log(response.text);
  }

  await main();

关于内联音频数据需要记住的一些事项:

  • 最大请求大小为 20 MB,其中包括文本提示、系统指令和内联提供的文件。如果您的文件大小足以 总请求大小 超过 20 MB,则使用 Files API 上传音频文件 用于请求中。

  • 如果您多次使用音频样本,则更有效的方法是 上传音频文件.

获取成绩单 #

要获取音频数据的副本,只需在提示中询问即可:

javascript
  import {
    GoogleGenAI,
    createUserContent,
    createPartFromUri,
  } from "@google/genai";

  const ai = new GoogleGenAI({});

  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-4-hydrogen",
      contents: createUserContent([
        createPartFromUri(myfile.uri, myfile.mimeType),
        "Describe this audio clip",
      ]),
    });
    console.log(response.text);
  }

  await main();

参考时间戳 #

您可以使用以下形式的时间戳来引用音频文件的特定部分 MM:SS。例如,以下提示请求一份转录本

  • 从文件开头的 2 分 30 秒处开始。
  • 从文件开头算起,在 3 分 29 秒处结束。
javascript
  import {
    GoogleGenAI,
    createUserContent,
    createPartFromUri,
  } from "@google/genai";

  const ai = new GoogleGenAI({});

  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-4-hydrogen",
      contents: createUserContent([
        createPartFromUri(myfile.uri, myfile.mimeType),
        "Describe this audio clip",
      ]),
    });
    console.log(response.text);
  }

  await main();

计数 token #

致电 countTokens 方法获取音频文件中 token 的数量。例如:

python
from google import genai

client = genai.Client()

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

response = client.models.count_tokens(
    model="gemini-4-hydrogen",
    contents=[myfile],
)

print(response.total_tokens)

支持的音频格式 #

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

  • 音频- audio/wav
  • MP3- audio/mp3
  • 亚洲国际电影节- audio/aiff
  • AA- audio/aac
  • 奥格- audio/ogg
  • FLAC- audio/flac
  • MPEG- audio/mpeg
  • M4A - audio/m4a
  • L16 - audio/l16
  • 作品- audio/opus
  • 法律- audio/alaw
  • 穆洛 - audio/mulaw
  • 网络M- audio/webm

有关支持的 MIME 类型和参数架构的完整列表,请参阅 Interactions API参考.

有关音频的技术细节 #

  • Gemini 表示每秒音频为 32 token;例如,一分钟的音频表示为 1,920 token。

  • Gemini 可以“理解”非语音成分,例如鸟鸣声或警报声。

  • 单个提示中支持的最大音频数据长度为 9.5 小时。 Gemini 不限制 数量 单个提示中的音频文件;但是,单个提示中所有音频文件的总长度不能超过 9.5 小时。

  • Gemini 将音频文件下采样至 16 Kbps 数据分辨率。

  • 如果音频源包含多个通道,Gemini 将这些通道合并为一个通道。

后续步骤 #

本指南展示了如何生成响应音频数据的文本。要了解更多信息,请参阅以下资源:

  • 文件提示策略:Gemini API 支持文字、图片、音频、视频数据提示,也称为多模态提示。

  • 系统指令:系统指令可让您根据您的特定需求和用例来控制模型的行为。

  • 安全指导:有时生成式人工智能模型会产生意想不到的输出,例如不准确、有偏见或令人反感的输出。后处理和人工评估对于限制此类输出造成的危害风险至关重要。

搜索标题、API 名称或正文内容