音声の理解

Gemini は音声入力を分析して理解できるため、次のようなユースケースが可能です。

  • 音声コンテンツの説明、要約、質問への回答を行う。
  • 音声の文字起こしを提供します。
  • 音声の特定のセグメントを分析する。

このガイドでは、Gemini API を使用して音声入力に対するテキスト レスポンスを生成する方法について説明します。

始める前に

Gemini API を呼び出す前に、任意の SDK がインストールされ、Gemini API キーが構成され、使用可能であることを確認してください。

入力音声

音声データは次の方法で Gemini に提供できます。

音声ファイルをアップロードする

Files API を使用して音声ファイルをアップロードできます。リクエストの合計サイズ(ファイル、テキスト プロンプト、システム インストラクションなど)が 20 MB を超える場合は、必ず Files API を使用してください。

次のコードは、音声ファイルをアップロードし、generateContent の呼び出しでそのファイルを使用します。

PythonJavaScriptGoREST
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 に渡すことができます。

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

インライン音声データに関する注意事項は次のとおりです。

  • リクエストの最大サイズは 20 MB です。これには、テキスト プロンプト、システム インストラクション、インラインで提供されるファイルが含まれます。ファイルのサイズが原因でリクエストの合計サイズが 20 MB を超える場合は、Files API を使用して、リクエストで使用する音声ファイルをアップロードします。
  • 音声サンプルを複数回使用する場合は、音声ファイルをアップロードすることをおすすめします。

文字起こしを取得する

音声データの文字起こしを取得するには、プロンプトで次のように尋ねます。

PythonJavaScriptGo
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 秒で終了します。

PythonJavaScriptGo
# 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 メソッドを呼び出して、音声ファイル内のトークン数を取得します。次に例を示します。

PythonJavaScriptGo
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 では、音声の 1 秒は 32 個のトークンとして表されます。たとえば、1 分間の音声は 1,920 個のトークンとして表されます。
  • Gemini は、英語の音声に対する回答のみを推測できます。
  • Gemini は、鳥のさえずりやサイレンなど、音声以外のコンポーネントを「理解」できます。
  • 1 つのプロンプトでサポートされる音声データの最大長は 9.5 時間です。Gemini では、1 つのプロンプト内の音声ファイルのに制限はありませんが、1 つのプロンプト内のすべての音声ファイルの合計長は 9.5 時間を超過できません。
  • Gemini は、音声ファイルを 16 Kbps のデータ解像度にダウンサンプリングします。
  • 音声ソースに複数のチャンネルが含まれている場合、Gemini はこれらのチャンネルを 1 つのチャンネルに結合します。

次のステップ

このガイドでは、音声データに応答してテキストを生成する方法について説明します。詳細については、次のリソースをご覧ください。

  • ファイル プロンプト戦略: Gemini API は、テキスト、画像、音声、動画データによるプロンプト(マルチモーダル プロンプト)をサポートしています。
  • システム指示: システム指示を使用すると、特定のニーズやユースケースに基づいてモデルの動作を制御できます。
  • 安全性に関するガイダンス: 生成 AI モデルは、不正確な出力、偏見のある出力、不適切な出力など、予期しない出力を生成することがあります。このような出力による被害のリスクを軽減するには、後処理と人間による評価が不可欠です。