Gemini는 오디오 입력을 분석하고 이해하여 다음과 같은 사용 사례를 지원할 수 있습니다.
- 오디오 콘텐츠에 관해 설명하거나 요약하거나 질문에 답변합니다.
- 오디오 스크립트를 제공합니다.
- 오디오의 특정 세그먼트를 분석합니다.
이 가이드에서는 Gemini API를 사용하여 오디오 입력에 대한 텍스트 응답을 생성하는 방법을 보여줍니다.
시작하기 전에
Gemini API를 호출하기 전에 선택한 SDK가 설치되어 있고 Gemini API 키가 구성되어 있고 사용할 준비가 되었는지 확인합니다.
입력 오디오
다음과 같은 방법으로 Gemini에 오디오 데이터를 제공할 수 있습니다.
generateContent
에 요청하기 전에 오디오 파일을 업로드합니다.generateContent
요청에 인라인 오디오 데이터를 전달합니다.
오디오 파일 업로드
Files API를 사용하여 오디오 파일을 업로드할 수 있습니다. 총 요청 크기 (파일, 텍스트 프롬프트, 시스템 안내 등 포함)가 20MB를 초과하는 경우 항상 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)
}
}
인라인 오디오 데이터와 관련하여 유의해야 할 사항은 다음과 같습니다.
- 최대 요청 크기는 20MB이며 여기에는 텍스트 프롬프트, 시스템 안내, 인라인으로 제공된 파일이 포함됩니다. 파일 크기로 인해 총 요청 크기가 20MB를 초과하는 경우 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분은 1,920개의 토큰으로 나타납니다.
- Gemini는 영어로 된 음성에 대한 대답만 추론할 수 있습니다.
- Gemini는 새의 지저귐이나 사이렌과 같은 비음성 구성요소를 '이해'할 수 있습니다.
- 단일 프롬프트에서 지원되는 최대 오디오 데이터 길이는 9.5시간입니다. Gemini는 단일 프롬프트의 오디오 파일 수를 제한하지 않습니다. 단, 단일 프롬프트의 모든 오디오 파일의 총 길이는 9.5시간을 초과할 수 없습니다.
- Gemini는 오디오 파일을 16Kbps 데이터 해상도로 다운샘플링합니다.
- 오디오 소스에 여러 채널이 포함된 경우 Gemini는 이러한 채널을 단일 채널로 결합합니다.
다음 단계
이 가이드에서는 오디오 데이터에 응답하여 텍스트를 생성하는 방법을 보여줍니다. 자세한 내용은 다음 리소스를 참고하세요.
- 파일 프롬프트 전략: Gemini API는 텍스트, 이미지, 오디오, 동영상 데이터를 사용한 프롬프트(다중 모달 프롬프트라고도 함)를 지원합니다.
- 시스템 안내: 시스템 안내를 사용하면 특정 요구사항 및 사용 사례에 따라 모델의 동작을 조정할 수 있습니다.
- 안전 가이드: 생성형 AI 모델이 부정확하거나 편향되거나 불쾌감을 주는 출력과 같은 예상치 못한 출력을 생성하는 경우가 있습니다. 이러한 출력으로 인한 피해 위험을 제한하려면 후처리 및 인간 평가가 필수적입니다.