Hiểu âm thanh

Gemini có thể phân tích và hiểu đầu vào âm thanh, cho phép các trường hợp sử dụng như sau:

  • Mô tả, tóm tắt hoặc trả lời câu hỏi về nội dung âm thanh.
  • Cung cấp bản chép lời của bản âm thanh.
  • Phân tích các phân đoạn cụ thể của âm thanh.

Hướng dẫn này sẽ hướng dẫn bạn cách sử dụng API Gemini để tạo câu trả lời văn bản cho đầu vào âm thanh.

Nhập âm thanh

Bạn có thể cung cấp dữ liệu âm thanh cho Gemini theo những cách sau:

Tải tệp âm thanh lên

Bạn có thể sử dụng API Tệp để tải tệp âm thanh lên. Luôn sử dụng API Tệp khi tổng kích thước yêu cầu (bao gồm cả tệp, lời nhắc văn bản, hướng dẫn hệ thống, v.v.) lớn hơn 20 MB.

Mã sau đây sẽ tải một tệp âm thanh lên, sau đó sử dụng tệp đó trong lệnh gọi đến 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

Để tìm hiểu thêm về cách làm việc với tệp phương tiện, hãy xem API Tệp.

Truyền dữ liệu âm thanh cùng dòng

Thay vì tải tệp âm thanh lên, bạn có thể truyền dữ liệu âm thanh nội tuyến trong yêu cầu đến 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)
  }
}

Một số điều cần lưu ý về dữ liệu âm thanh nội tuyến:

  • Kích thước yêu cầu tối đa là 20 MB, bao gồm cả lời nhắc văn bản, hướng dẫn hệ thống và các tệp được cung cấp cùng dòng. Nếu kích thước tệp của bạn khiến tổng kích thước yêu cầu vượt quá 20 MB, hãy sử dụng API Tệp để tải tệp âm thanh lên để sử dụng trong yêu cầu.
  • Nếu bạn sử dụng một đoạn âm thanh nhiều lần, thì bạn nên tải tệp âm thanh lên để đạt được hiệu quả cao hơn.

Tải bản chép lời

Để nhận bản chép lời của dữ liệu âm thanh, bạn chỉ cần yêu cầu trong lời nhắc:

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)
  }
}

Tham khảo dấu thời gian

Bạn có thể tham chiếu đến các phần cụ thể của tệp âm thanh bằng cách sử dụng dấu thời gian ở dạng MM:SS. Ví dụ: câu lệnh sau yêu cầu bản chép lời

  • Bắt đầu từ 2 phút 30 giây tính từ đầu tệp.
  • Kết thúc vào 3 phút 29 giây kể từ đầu tệp.

# 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."),
}

Đếm mã thông báo

Gọi phương thức countTokens để đếm số lượng mã thông báo trong một tệp âm thanh. Ví dụ:

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)

Định dạng âm thanh được hỗ trợ

Gemini hỗ trợ các loại MIME định dạng âm thanh sau:

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

Thông tin chi tiết về kỹ thuật của âm thanh

  • Gemini biểu thị mỗi giây âm thanh bằng 32 mã thông báo; ví dụ: một phút âm thanh được biểu thị bằng 1.920 mã thông báo.
  • Gemini chỉ có thể suy luận câu trả lời cho lời nói bằng tiếng Anh.
  • Gemini có thể "hiểu" các thành phần không phải lời nói, chẳng hạn như tiếng chim hót hoặc tiếng còi.
  • Thời lượng tối đa được hỗ trợ của dữ liệu âm thanh trong một câu lệnh là 9,5 giờ. Gemini không giới hạn số lượng tệp âm thanh trong một câu lệnh; tuy nhiên, tổng thời lượng kết hợp của tất cả tệp âm thanh trong một câu lệnh không được vượt quá 9,5 giờ.
  • Gemini giảm mẫu tệp âm thanh xuống độ phân giải dữ liệu 16 Kb/giây.
  • Nếu nguồn âm thanh chứa nhiều kênh, Gemini sẽ kết hợp các kênh đó thành một kênh duy nhất.

Bước tiếp theo

Hướng dẫn này cho biết cách tạo văn bản để phản hồi dữ liệu âm thanh. Để tìm hiểu thêm, hãy xem các tài nguyên sau:

  • Chiến lược nhắc tệp: Gemini API hỗ trợ nhắc bằng dữ liệu văn bản, hình ảnh, âm thanh và video, còn gọi là nhắc đa phương thức.
  • Hướng dẫn hệ thống: Hướng dẫn hệ thống cho phép bạn điều hướng hành vi của mô hình dựa trên các nhu cầu và trường hợp sử dụng cụ thể.
  • Hướng dẫn an toàn: Đôi khi, các mô hình AI tạo sinh tạo ra kết quả không mong muốn, chẳng hạn như kết quả không chính xác, thiên vị hoặc phản cảm. Quá trình xử lý hậu kỳ và đánh giá của con người là điều cần thiết để hạn chế rủi ro gây hại từ những kết quả như vậy.