Бесплатный урок Официальный курс Gemini API Cookbook на русском
Урок 02 · Текст · ~5 мин

Работа со звуком

Урок 2 из 71 курса «Gemini API: быстрый старт»: официальный курс Gemini API Cookbook (Гугл Джемини) на русском языке. Этот урок бесплатный.

Copyright 2026 Google LLC.
# @title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Gemini API: Краткое руководство по работе с аудио

Изображение (внешний источник)

Этот блокнот содержит пример того, как использовать Gemini Flash с аудиофайлом. В данном случае Вы будете использовать звукозапись обращения президента Джона Ф. Кеннеди «О положении в стране» 1961 года.

Примечание: Этот блокнот использует Interactions API, новейший способ взаимодействия с моделями Gemini. Ищете версию generateContent? Проверьте архивную ветку.

Настройка

Установка зависимостей

%pip install -U -q "google-genai>=2.9.0"  # 2.0 for Interactions API

Настройка ключа API

Для выполнения следующей ячейки Ваш ключ API должен быть сохранен в Colab Secret с именем GEMINI_API_KEY. Если у Вас еще нет ключа API или Вы не знаете, как создать Colab Secret, см. Аутентификация для пошагового руководства.

from google.colab import userdata
from google import genai

GEMINI_API_KEY = userdata.get('GEMINI_API_KEY')
client = genai.Client(api_key=GEMINI_API_KEY)

Выберите модель, которую Вы хотите использовать в этом руководстве:

MODEL_ID = "gemini-3.8-flash" # @param ["gemini-4-argon", "gemini-3.1-pro-preview", "gemini-3.8-flash", "gemini-3.7-flash", "gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-2.5-pro"] {"allow-input": true, "isTemplate": true}

Загрузка аудиофайла с помощью File API

Чтобы использовать аудиофайл в Вашем запросе, Вы должны сначала загрузить его с помощью File API.

URL = "https://storage.googleapis.com/generativeai-downloads/data/State_of_the_Union_Address_30_January_1961.mp3"
!wget -q $URL -O sample.mp3
your_audio_file = client.files.upload(file='sample.mp3')

Использование файла в Вашем запросе

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        {"type": "text", "text": "Listen carefully to the following audio file. Provide a brief summary."},
        {"type": "audio", "uri": your_audio_file.uri},
    ],
)

print(interaction.steps[-1].content[0].text)
In his first State of the Union address on January 30, 1961, President John F. Kennedy presents a candid assessment of a nation facing both "national peril and national opportunity." He details a struggling domestic economy marked by recession, high unemployment, and stagnant growth, proposing a series of legislative measures—including minimum wage increases, urban redevelopment, and expanded unemployment benefits—to stimulate recovery. 

On the international front, Kennedy addresses the heightening tensions of the Cold War, highlighting crises in Asia, Africa, and Latin America. He calls for a significant strengthening of U.S. military capabilities, specifically through increased airlift capacity and accelerated missile and submarine programs. Simultaneously, he champions a proactive foreign policy focused on international development, proposing the "Alliance for Progress" for Latin America and the creation of the Peace Corps. Kennedy concludes by emphasizing the need for scientific cooperation, arms control, and the unwavering dedication of the American people to navigate the challenging years ahead.

Встроенное аудио

Для небольших запросов Вы можете встроить аудиоданные в запрос, как и изображения. Аудиоданные должны быть закодированы в base64 для отправки с запросом. Используйте, например, PyDub, чтобы обрезать первые 10 секунд аудио:

%pip install -Uq pydub
from pydub import AudioSegment
 from .audio_segment import AudioSegment
  File "/usr/local/google/home/giom/.gemini/jetski/scratch/cookbook-agentB-interactions/.venv/lib/python3.13/site-packages/pydub/audio_segment.py", line 11, in <module>
    from .utils import mediainfo_json, fsdecode
  File "/usr/local/google/home/giom/.gemini/jetski/scratch/cookbook-agentB-interactions/.venv/lib/python3.13/site-packages/pydub/utils.py", line 16, in <module>
    import pyaudioop as audioop
ModuleNotFoundError: No module named 'pyaudioop'
sound = AudioSegment.from_mp3("sample.mp3")
Traceback (most recent call last):
  File "/tmp/execute_notebook.py", line 103, in execute_notebook
    result = exec(compile(prepared, f"{name}:cell_{i}", 'exec'), ns)
  File "Audio.ipynb:cell_22", line 1, in <module>
NameError: name 'AudioSegment' is not defined
sound[:10000] # slices are in ms
Traceback (most recent call last):
  File "/tmp/execute_notebook.py", line 103, in execute_notebook
    result = exec(compile(prepared, f"{name}:cell_{i}", 'exec'), ns)
  File "Audio.ipynb:cell_23", line 1, in <module>
NameError: name 'sound' is not defined. Did you mean: 'round'?

Добавьте его в список частей в запросе:

import base64

audio_data = base64.b64encode(sound[:10000].export().read()).decode('utf-8')

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        {"type": "text", "text": "Describe this audio clip"},
        {"type": "audio", "data": audio_data, "mime_type": "audio/mp3"},
    ],
)

print(interaction.steps[-1].content[0].text)
Traceback (most recent call last):
  File "/tmp/execute_notebook.py", line 103, in execute_notebook
    result = exec(compile(prepared, f"{name}:cell_{i}", 'exec'), ns)
  File "Audio.ipynb:cell_25", line 3, in <module>
NameError: name 'sound' is not defined. Did you mean: 'round'?

Обратите внимание на следующее при предоставлении аудио в виде встроенных данных:

  • Максимальный размер запроса составляет 100 МБ, что включает текстовые запросы, системные инструкции и файлы, предоставленные встроенно. Если размер Вашего файла приведет к превышению общего размера запроса в 100 МБ, то используйте File API для загрузки файлов.
  • Если Вы используете аудиосэмпл несколько раз, эффективнее использовать File API.

Получение транскрипции аудиофайла

Чтобы получить транскрипцию, просто запросите ее в запросе. Например:

prompt = "Generate a transcript of the speech."

interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        {"type": "text", "text": prompt},
        {"type": "audio", "uri": your_audio_file.uri},
    ],
)

from IPython.display import Markdown
display(Markdown(interaction.steps[-1].content[0].text))

Ссылки на временные метки в аудиофайле

Запрос может указывать временные метки в формате MM:SS для ссылки на определенные разделы в аудиофайле. Например:

# Create a prompt containing timestamps. prompt = "Provide a transcript of the speech between the timestamps 02:30 and 03:29." interaction = client.interactions.create( model=MODEL_ID, input=[ {"type": "text", "text": prompt}, {"type": "audio", "uri": your_audio_file.uri}, ], ) display(Markdown(interaction.steps[-1].content[0].text))
Here's a transcript of the speech between the timestamps 02:30 and 03:29:

To be back among so many friends is a happy one. I am confident that that friendship will continue. Our Constitution wisely assigns both joint and separate roles to each branch of the Government; and a President and a Congress who hold each other in mutual respect will neither permit nor attempt any trespass. For my part, I shall withhold from neither the Congress nor the people any fact or report, past, present, or future, which is necessary for an informed judgment of our conduct and hazards. I shall neither shift the burden of executive decisions to the Congress, nor avoid responsibility for the outcome of those decisions.

Использование видео с YouTube

from IPython.display import display, Markdown

youtube_url = "https://www.youtube.com/watch?v=RDOMKIw1aF4" # @param {type:"string"}

prompt = """
    Analyze the following YouTube video content. Provide a concise summary covering:

    1.  **Main Thesis/Claim:** What is the central point the creator is making?
    2.  **Key Topics:** List the main subjects discussed, referencing specific examples or technologies mentioned (e.g., AI models, programming languages, projects).
    3.  **Call to Action:** Identify any explicit requests made to the viewer.
    4.  **Summary:** Provide a concise summary of the video content.

    Use the provided title, chapter timestamps/descriptions, and description text for your analysis.
"""
# Analyze the video
interaction = client.interactions.create(
    model=MODEL_ID,
    input=[
        {"type": "text", "text": prompt},
        {"type": "video", "uri": youtube_url},
    ],
)
display(Markdown(interaction.steps[-1].content[0].text))
<IPython.core.display.Markdown object>

Подсчет аудиотокенов

Вы можете подсчитать количество токенов в Вашем аудиофайле с помощью метода count_tokens.

Аудиофайлы имеют фиксированную скорость токенов в секунду (более подробная информация в специальном кратком руководстве по подсчету токенов).

count_tokens_response = client.models.count_tokens(
    model=MODEL_ID,
    contents=[your_audio_file],
)

print("Audio file tokens:",count_tokens_response.total_tokens)
Audio file tokens: 83528

Следующие шаги

Полезные ссылки на API:

Более подробная информация о возможностях зрения Gemini API в документации.

Если Вы хотите узнать о File API, ознакомьтесь с его справочником API или кратким руководством по File API.

Связанные примеры

Ознакомьтесь с этим примером использования аудиофайлов, чтобы получить больше идей о том, что Gemini API может с ними делать: * Делитесь голосовыми заметками с Gemini API и обдумывайте идеи

Продолжайте изучение Gemini API

Ознакомьтесь с кратким руководством по аудио, чтобы узнать о другом типе медиафайлов, затем узнайте больше о запросах с медиафайлами в документации, включая поддерживаемые форматы и максимальную длину для аудиофайлов.

Урок входит в темы

Полезные гиды