Gemini 可分析及理解音訊輸入內容,因此可用於下列用途:
- 描述、摘要或回答音訊內容相關問題。
- 提供音訊轉錄稿。
- 分析音訊的特定片段。
本指南說明如何使用 Gemini API,針對音訊輸入內容產生文字回應。
事前準備
呼叫 Gemini API 前,請確認您已安裝所選 SDK,並設定 Gemini API 金鑰,以便使用。
輸入音訊
您可以透過下列方式向 Gemini 提供音訊資料:
- 請先上傳音訊檔案,再向 generateContent提出要求。
- 透過要求傳遞內嵌音訊資料至 generateContent。
上傳音訊檔案
您可以使用 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-2.5-flash", contents=["Describe this audio clip", myfile]
)
print(response.text)
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-2.5-flash",
    contents: createUserContent([
      createPartFromUri(myfile.uri, myfile.mimeType),
      "Describe this audio clip",
    ]),
  });
  console.log(response.text);
}
await main();
Go
package main
import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)
func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }
  localAudioPath := "/path/to/sample.mp3"
  uploadedFile, _ := client.Files.UploadFromPath(
      ctx,
      localAudioPath,
      nil,
  )
  parts := []*genai.Part{
      genai.NewPartFromText("Describe this audio clip"),
      genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
  }
  contents := []*genai.Content{
      genai.NewContentFromParts(parts, genai.RoleUser),
  }
  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      contents,
      nil,
  )
  fmt.Println(result.Text())
}
REST
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" \
  -H "x-goog-api-key: $GEMINI_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.5-flash:generateContent" \
    -H "x-goog-api-key: $GEMINI_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,而非上傳音訊檔案:
Python
from google import genai
from google.genai import types
with open('path/to/small-sample.mp3', 'rb') as f:
    audio_bytes = f.read()
client = genai.Client()
response = client.models.generate_content(
  model='gemini-2.5-flash',
  contents=[
    'Describe this audio clip',
    types.Part.from_bytes(
      data=audio_bytes,
      mime_type='audio/mp3',
    )
  ]
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
import * as fs from "node:fs";
const ai = new GoogleGenAI({});
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.5-flash",
  contents: contents,
});
console.log(response.text);
Go
package main
import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)
func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }
  audioBytes, _ := os.ReadFile("/path/to/small-sample.mp3")
  parts := []*genai.Part{
      genai.NewPartFromText("Describe this audio clip"),
    &genai.Part{
      InlineData: &genai.Blob{
        MIMEType: "audio/mp3",
        Data:     audioBytes,
      },
    },
  }
  contents := []*genai.Content{
      genai.NewContentFromParts(parts, genai.RoleUser),
  }
  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      contents,
      nil,
  )
  fmt.Println(result.Text())
}
關於內嵌音訊資料,請注意下列事項:
- 要求大小上限為 20 MB,其中包括文字提示、系統操作說明和內嵌檔案。如果檔案大小會導致總要求大小超過 20 MB,請使用 Files API 上傳音訊檔案,以便在要求中使用。
- 如果要多次使用音訊樣本,建議上傳音訊檔案。
取得轉錄稿
如要取得音訊資料的轉錄稿,只要在提示中提出要求即可:
Python
from google import genai
client = genai.Client()
myfile = client.files.upload(file='path/to/sample.mp3')
prompt = 'Generate a transcript of the speech.'
response = client.models.generate_content(
  model='gemini-2.5-flash',
  contents=[prompt, myfile]
)
print(response.text)
JavaScript
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({});
const myfile = await ai.files.upload({
  file: "path/to/sample.mp3",
  config: { mimeType: "audio/mpeg" },
});
const result = await ai.models.generateContent({
  model: "gemini-2.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
    "Generate a transcript of the speech.",
  ]),
});
console.log("result.text=", result.text);
Go
package main
import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)
func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }
  localAudioPath := "/path/to/sample.mp3"
  uploadedFile, _ := client.Files.UploadFromPath(
      ctx,
      localAudioPath,
      nil,
  )
  parts := []*genai.Part{
      genai.NewPartFromText("Generate a transcript of the speech."),
      genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
  }
  contents := []*genai.Content{
      genai.NewContentFromParts(parts, genai.RoleUser),
  }
  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      contents,
      nil,
  )
  fmt.Println(result.Text())
}
參照時間戳記
您可以使用 MM:SS 格式的時間戳記,參照音訊檔案的特定部分。舉例來說,下列提示會要求轉錄稿,
- 從檔案開頭開始播放 2 分 30 秒。
- 結束時間為檔案開頭的 3 分 29 秒。 
Python
# Create a prompt containing timestamps.
prompt = "Provide a transcript of the speech from 02:30 to 03:29."
JavaScript
// Create a prompt containing timestamps.
const prompt = "Provide a transcript of the speech from 02:30 to 03:29."
Go
package main
import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)
func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }
  localAudioPath := "/path/to/sample.mp3"
  uploadedFile, _ := client.Files.UploadFromPath(
      ctx,
      localAudioPath,
      nil,
  )
  parts := []*genai.Part{
      genai.NewPartFromText("Provide a transcript of the speech " +
                            "between the timestamps 02:30 and 03:29."),
      genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
  }
  contents := []*genai.Content{
      genai.NewContentFromParts(parts, genai.RoleUser),
  }
  result, _ := client.Models.GenerateContent(
      ctx,
      "gemini-2.5-flash",
      contents,
      nil,
  )
  fmt.Println(result.Text())
}
計算符記
呼叫 countTokens 方法,即可取得音訊檔案中的符記數量。例如:
Python
from google import genai
client = genai.Client()
response = client.models.count_tokens(
  model='gemini-2.5-flash',
  contents=[myfile]
)
print(response)
JavaScript
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({});
const myfile = await ai.files.upload({
  file: "path/to/sample.mp3",
  config: { mimeType: "audio/mpeg" },
});
const countTokensResponse = await ai.models.countTokens({
  model: "gemini-2.5-flash",
  contents: createUserContent([
    createPartFromUri(myfile.uri, myfile.mimeType),
  ]),
});
console.log(countTokensResponse.totalTokens);
Go
package main
import (
  "context"
  "fmt"
  "os"
  "google.golang.org/genai"
)
func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, nil)
  if err != nil {
      log.Fatal(err)
  }
  localAudioPath := "/path/to/sample.mp3"
  uploadedFile, _ := client.Files.UploadFromPath(
      ctx,
      localAudioPath,
      nil,
  )
  parts := []*genai.Part{
      genai.NewPartFromURI(uploadedFile.URI, uploadedFile.MIMEType),
  }
  contents := []*genai.Content{
      genai.NewContentFromParts(parts, genai.RoleUser),
  }
  tokens, _ := client.Models.CountTokens(
      ctx,
      "gemini-2.5-flash",
      contents,
      nil,
  )
  fmt.Printf("File %s is %d tokens\n", localAudioPath, 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 可以「理解」非語音內容,例如鳥鳴或警鈴聲。
- 單一提示支援的音訊資料長度上限為 9.5 小時。Gemini 不會限制單一提示中的音訊檔案數量,但單一提示中所有音訊檔案的總長度不得超過 9.5 小時。
- Gemini 會將音訊檔案降採樣至 16 Kbps 資料解析度。
- 如果音訊來源包含多個頻道,Gemini 會將這些頻道合而為一。
後續步驟
本指南說明如何根據音訊資料產生文字。如要進一步瞭解相關內容,請參閱下列資源: