Gemini 可回應音訊提示。舉例來說,Gemini 可以:
- 描述、摘要或回答音訊內容相關問題。
- 提供音訊轉錄稿。
- 針對音訊的特定片段提供答案或轉錄稿。
本指南將示範使用 Gemini API 與音訊檔案和音訊內容互動的不同方式。
支援的音訊格式
Gemini 支援下列音訊格式的 MIME 類型:
- WAV -
audio/wav
- MP3 -
audio/mp3
- AIFF -
audio/aiff
- AAC -
audio/aac
- OGG Vorbis -
audio/ogg
- FLAC -
audio/flac
音訊技術詳細資料
Gemini 對音訊有以下規則:
- Gemini 會將每秒的音訊表示為 32 個符記,例如 1 分鐘的音訊會以 1,920 個符記表示。
- Gemini 只能針對英文語音推斷回覆。
- Gemini 可以「理解」非語音內容,例如鳥鳴或警鈴聲。
- 單一提示支援的音訊資料長度上限為 9.5 小時。Gemini 不會限制單一提示中的音訊檔案數量,但單一提示中所有音訊檔案的總長度不得超過 9.5 小時。
- Gemini 會將音訊檔案降採樣至 16 Kbps 資料解析度。
- 如果音訊來源含有多個聲道,Gemini 會將這些聲道合併為單一聲道。
事前準備:設定專案和 API 金鑰
在呼叫 Gemini API 之前,您需要設定專案並設定 API 金鑰。
將音訊檔案提供給 Gemini
你可以透過下列任一方式,將音訊檔案提供給 Gemini:
上傳音訊檔案並產生內容
您可以使用 File API 上傳任何大小的音訊檔案。如果總要求大小 (包括檔案、文字提示、系統指示等) 超過 20 MB,請一律使用 File API。
呼叫 media.upload
,使用 File API 上傳檔案。以下程式碼會上傳音訊檔案,然後在呼叫 models.generateContent
時使用該檔案。
from google import genai
client = genai.Client()
myfile = client.files.upload(file='media/sample.mp3')
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=['Describe this audio clip', myfile]
)
print(response.text)
取得檔案的中繼資料
您可以呼叫 files.get
,驗證 API 是否已成功儲存上傳的檔案,並取得其中繼資料。
myfile = client.files.upload(file='media/sample.mp3')
file_name = myfile.name
myfile = client.files.get(name=file_name)
print(myfile)
列出已上傳的檔案
你可以上傳多個音訊檔案 (和其他類型的檔案)。以下程式碼會產生所有上傳檔案的清單:
print('My files:')
for f in client.files.list():
print(' ', f.name)
刪除已上傳的檔案
檔案會在 48 小時後自動刪除。您也可以手動刪除已上傳的檔案。例如:
myfile = client.files.upload(file='media/sample.mp3')
client.files.delete(name=myfile.name)
在要求中以內嵌資料的形式提供音訊檔案
您可以改為在包含提示的相同呼叫中傳遞音訊資料,而非上傳音訊檔案。
接著,將下載的音訊檔案和提示傳送至 Gemini:
from google.genai import types
with open('media/small-sample.mp3', 'rb') as f:
image_bytes = f.read()
response = client.models.generate_content(
model='gemini-2.0-flash',
contents=[
'Describe this audio clip',
types.Part.from_bytes(
data=image_bytes,
mime_type='audio/mp3',
)
]
)
print(response.text)
請注意,以下是提供音訊做為內嵌資料的注意事項:
- 要求大小上限為 20 MB,其中包括文字提示、系統操作說明和內嵌檔案。如果檔案大小會導致總要求大小超過 20 MB,請使用 File API 上傳檔案,以便在要求中使用。
- 如果您要多次使用音訊樣本,建議您使用 File API,這樣效率會更高。
更多處理音訊的方式
本節將介紹幾種可進一步利用音訊的其他方法。
取得音訊檔案的轉錄稿
如要取得轉錄稿,只要在提示中要求即可。例如:
myfile = client.files.upload(file='media/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)
參照音訊檔案中的時間戳記
提示可以指定 MM:SS
格式的時間戳記,以便參照音訊檔案中的特定部分。舉例來說,下列提示會要求轉錄稿,其內容如下:
- 從檔案開頭開始播放 2 分 30 秒。
- 結束時間為檔案開頭的 3 分 29 秒。
# Create a prompt containing timestamps.
prompt = "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)
後續步驟
本指南說明如何使用 File API 上傳音訊檔案,然後從音訊輸入內容產生文字輸出內容。如要進一步瞭解相關內容,請參閱下列資源: