# Gemini Media

> 使用 Gemini API（Nano Banana 图像、Veo 视频、Gemini TTS 语音与音频理解）完成“生成 + 理解”的端到端多模态媒体工作流与代码模板。

- Skill: `xsir0/gemini-media` (Agent Skill, multi-file: 9 files)
- Install (CLI): `npx skillmds@latest add xsir0/gemini-media`
- Raw SKILL.md: https://api.skillmd.com/api/skills/xsir0/gemini-media/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Integrations & APIs
- License: MIT
- Author: Xsir0 (https://skillmd.com/u/xsir0)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/xsir0/gemini-media

---


# Gemini 多模态媒体（图像/视频/语音）Skill

## 1. 目标与适用范围

本 Skill 将 Gemini API 的 6 类能力聚合为一个可复用的工作流与实现模板：

- 图片生成（Nano Banana：文本生图、图文编辑、多轮迭代）
- 图片理解（caption/VQA/分类/对比，多图提示；支持内嵌与 Files API）
- 视频生成（Veo 3.1：文本生视频、纵横比/分辨率控制、参考图引导、首尾帧、视频扩展、原生音频）
- 视频理解（上传/内嵌/YouTube URL；摘要、问答、基于时间戳引用）
- 语音生成（Gemini 原生 TTS：单说话人、多说话人；风格/口音/节奏/语气可控）
- 音频理解（上传/内嵌；描述、转写、时间段转写、token 统计）

> 约定：本 Skill 以官方 Google Gen AI SDK（Python/REST）为主线；当前仅提供 Python/REST 示例。如你在项目中已有不同语言或框架封装，请将本 Skill 的“请求结构、模型选择与输入输出规范”映射到你的封装层。

---

## 2. 快速路由（先决定用哪个能力）

1) **你要产出图片吗？**
- 需要“从无到有生成图片”或“基于图编辑生成新图” → 使用 **Nano Banana 图像生成**（见第 5 章）

2) **你要读懂图片吗？**
- 需要识别、描述、问答、对比、抽取信息 → 使用 **图片理解**（见第 6 章）

3) **你要产出视频吗？**
- 需要生成 8 秒视频（可带原生音频） → 使用 **Veo 3.1 视频生成**（见第 7 章）

4) **你要读懂视频吗？**
- 需要总结/问答/抽取片段并引用时间戳 → 使用 **视频理解**（见第 8 章）

5) **你要把文本念出来吗？**
- 需要可控朗读、播客/有声书风格等 → 使用 **语音生成（TTS）**（见第 9 章）

6) **你要读懂音频吗？**
- 需要描述音频内容、转写、按时间段转写、统计 token → 使用 **音频理解**（见第 10 章）

---

## 3. 统一的工程约束与输入输出规范（必读）

### 3.0 运行前准备（依赖与工具）

- Python 3.x（与项目实际版本保持一致）
- 安装 SDK 与图像处理依赖（示例）：
```bash
pip install google-genai pillow
```
- REST 示例只需 `curl`；若要解析图片 Base64，建议安装 `jq`（可选）。

### 3.1 认证与环境变量

- 建议将 API Key 放入环境变量：`GEMINI_API_KEY`
- REST 请求统一使用 `x-goog-api-key: $GEMINI_API_KEY`

### 3.2 两种“文件输入”方式：Inline vs Files API

**Inline（内嵌字节/Base64）**
- 优点：调用链短，适合小文件。
- 关键约束：**总请求大小**（文本提示 + 系统指令 + 内嵌字节）通常有 20MB 级别上限（图像/音频文档均提示此点）。

**Files API（先上传再引用）**
- 优点：适合大文件、重复使用同一文件、多轮对话。
- 典型流程：
  1. `files.upload(...)`（SDK）或 `POST /upload/v1beta/files`（REST resumable）
  2. 在 `generateContent` 中使用 `file_data` / `file_uri` 引用上传结果

> 技术落地建议：在工程里实现一个 `ensure_file_uri()`：当文件超过阈值（例如 10~15MB 预警）或被多次复用时，自动走 Files API。

### 3.3 输出“二进制媒体”的统一处理

- **图片**：通常在响应的 `parts` 中以 `inline_data`（Base64）出现；SDK 中可用 `part.as_image()` 或自行 Base64 解码保存为 PNG/JPG。
- **语音（TTS）**：返回的通常是 **PCM** 字节流（Base64）；需保存为 `.pcm` 或封装成 `.wav`（常用 24kHz、16-bit、mono）。
- **视频（Veo）**：是 **长耗时异步任务**，需要轮询 operation；完成后下载文件（或通过返回的 URI 下载）。

---

## 4. 模型选择矩阵（务必按场景选型）

> 重要：模型名称、版本、限制与配额可能随时间变更；请在使用前对照官方文档确认。本文最后更新：2026-01-22。

### 4.1 图像生成（Nano Banana）
- **gemini-2.5-flash-image**：速度与吞吐优先，适合高频低延迟生成/编辑。
- **gemini-3-pro-image-preview**：更强的指令遵循与高保真文本渲染，更适合专业资产输出与复杂编辑。

### 4.2 通用图像/视频/音频理解
- 文档示例使用 `gemini-3-flash-preview` 处理图片、视频、音频理解（你也可按质量/成本选用更强型号）。

### 4.3 视频生成（Veo）
- 示例模型：`veo-3.1-generate-preview`（生成 8 秒视频并可原生生成音频）。

### 4.4 语音生成（TTS）
- 示例模型：`gemini-2.5-flash-preview-tts`（原生 TTS，当前为预览版）。

---

## 5. 图片生成（Nano Banana）

### 5.1 文本生图（Text-to-Image）

**SDK（Python）最小模板**
```python
from google import genai

client = genai.Client()

resp = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=["Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"],
)

# 解析返回 parts：既可能有 text，也可能有 inline_data（图片）
for part in resp.parts:
    if part.text:
        print(part.text)
    elif part.inline_data:
        img = part.as_image()
        img.save("out.png")
```

**REST（带 imageConfig）最小模板**
```bash
curl -s -X POST   "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent"   -H "x-goog-api-key: $GEMINI_API_KEY"   -H "Content-Type: application/json"   -d '{
    "contents":[{"parts":[{"text":"Create a picture of a nano banana dish in a fancy restaurant with a Gemini theme"}]}],
    "generationConfig": {"imageConfig": {"aspectRatio":"16:9"}}
  }'
```

**REST 解析图片（Base64 解码）示例**
```bash
curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents":[{"parts":[{"text":"A minimal studio product shot of a nano banana"}]}]}' \
  | jq -r '.candidates[0].content.parts[] | select(.inline_data) | .inline_data.data' \
  | base64 --decode > out.png

# macOS 可使用：base64 -D > out.png
```

### 5.2 图文编辑（Text-and-Image-to-Image）

用途：给定一张图，通过文本指令**添加/删除/修改元素**、变换风格、调色等。

**SDK（Python）最小模板**
```python
from google import genai
from PIL import Image

client = genai.Client()

prompt = "Add a nano banana on the table, keep lighting consistent, cinematic tone."
img = Image.open("input.png")

resp = client.models.generate_content(
    model="gemini-2.5-flash-image",
    contents=[prompt, img],
)

for part in resp.parts:
    if part.inline_data:
        part.as_image().save("edited.png")
```

### 5.3 多轮图像迭代（Multi-turn editing）

最佳实践：使用 chat 进行连续迭代（比如先生成，再“只改某个区域/元素”，再“做同风格变体”）。  
要输出“文本+图片”混合结果时，将 `response_modalities` 设置为 `['TEXT', 'IMAGE']`。

### 5.4 图像配置（ImageConfig）

可在 `generationConfig.imageConfig` 或 SDK 的 config 中设置：
- `aspectRatio`：例如 `16:9`、`1:1`。
- `imageSize`：例如 `2K`、`4K`（高分辨率通常更慢/更贵，且不同模型支持范围可能不同）。

---

## 6. 图片理解（Image Understanding）

### 6.1 输入图片的两种方式

- **内嵌图片数据**：适合小文件（总请求大小 < 20MB）。
- **Files API 上传**：更适合大文件或在多个请求中复用图片。

### 6.2 内嵌图片（Python）最小模板
```python
from google import genai
from google.genai import types

client = genai.Client()

with open("image.jpg", "rb") as f:
    image_bytes = f.read()

resp = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[
        types.Part.from_bytes(data=image_bytes, mime_type="image/jpeg"),
        "Caption this image, and list any visible brands.",
    ],
)
print(resp.text)
```

### 6.3 Files API 上传并引用（Python）最小模板
```python
from google import genai

client = genai.Client()
my_file = client.files.upload(file="image.jpg")

resp = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[my_file, "Caption this image."],
)
print(resp.text)
```

### 6.4 多图提示

把多张图片作为多个 `Part` 追加到同一个 `contents` 中即可；可混用“上传引用”和“内嵌字节”。

---

## 7. 视频生成（Veo 3.1）

### 7.1 核心特点（你必须知道）
- 生成 **8 秒**高保真视频，可选 720p / 1080p / 4k，并支持原生生成音频（对话、环境声、音效）。
- 支持：
  - 纵横比（16:9 / 9:16）
  - 视频扩展（延长已生成视频；通常限制在 720p）
  - 首帧/尾帧指定（frame-specific）
  - 最多 3 张参考图引导（image-based direction）

### 7.2 SDK（Python）最小模板：异步轮询 + 下载
```python
import time
from google import genai
from google.genai import types

client = genai.Client()

prompt = "A cinematic shot of a cat astronaut walking on the moon. Include subtle wind ambience."
op = client.models.generate_videos(
    model="veo-3.1-generate-preview",
    prompt=prompt,
    config=types.GenerateVideosConfig(resolution="1080p"),
)

while not op.done:
    time.sleep(10)
    op = client.operations.get(op)

video = op.response.generated_videos[0].video
client.files.download(file=video)
video.save("out.mp4")
```

### 7.3 REST 最小模板：predictLongRunning + 轮询 + 下载

关键点：Veo 的 REST 接口通过 `:predictLongRunning` 返回 operation name，然后轮询 `GET /v1beta/{operation_name}`，done 后从响应里取视频 URI 下载。

### 7.4 常用控制项（建议统一封装）

- `aspectRatio`: `"16:9"` 或 `"9:16"`
- `resolution`: `"720p" | "1080p" | "4k"`（更高分辨率通常更慢/更贵）
- 写提示词时：用引号写对白；明确写 SFX 和环境声；使用影视镜头语言（机位、运动、构图、镜头效果、氛围）。
- 负向约束：若接口支持 negative prompt 字段，优先使用；否则用“列出你不想看到的元素”的方式表达。

### 7.5 重要限制（工程上要做兜底）

- 生成延迟可在秒级到分钟级波动；需要超时与重试策略。
- 生成视频在服务端只保留有限时间（需及时下载保存）。
- 输出会带 SynthID 水印。

**轮询兜底（带超时/退避）伪代码**
```python
deadline = time.time() + 300  # 5 min
sleep_s = 2
while not op.done and time.time() < deadline:
    time.sleep(sleep_s)
    sleep_s = min(sleep_s * 1.5, 15)
    op = client.operations.get(op)
if not op.done:
    raise TimeoutError("video generation timed out")
```

---

## 8. 视频理解（Video Understanding）

### 8.1 视频输入方式
- **Files API 上传视频**：当文件 > 100MB、视频时长 > ~1 分钟，或需要多次复用时推荐。
- **内嵌视频数据**：适用于更小文件。
- **直接传 YouTube URL**：可用于公开视频分析。

### 8.2 Files API（Python）最小模板
```python
from google import genai

client = genai.Client()
myfile = client.files.upload(file="sample.mp4")

resp = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=[myfile, "Summarize this video. Provide timestamps for key events."],
)
print(resp.text)
```

### 8.3 时间戳引用的提示词策略
- 让模型输出 “(mm:ss)” 的分段要点。
- 明确要求“引用具体时间段的证据”，并把下游结构化抽取（JSON）放在同一个提示里（如你需要）。

---

## 9. 语音生成（文本转语音，TTS）

### 9.1 关键定位
- 原生 TTS：用于“精确朗读文本 + 风格可控”（播客、有声书、广告配音等）。
- 与 Live API 区分：Live API 更偏交互式、非结构化音频与多模态会话；TTS 更偏“可控朗读”。

### 9.2 单说话人 TTS（Python）最小模板
```python
from google import genai
from google.genai import types
import wave

def save_wav(filename: str, pcm: bytes, rate=24000, channels=1, sample_width=2):
    with wave.open(filename, "wb") as wf:
        wf.setnchannels(channels)
        wf.setsampwidth(sample_width)
        wf.setframerate(rate)
        wf.writeframes(pcm)

client = genai.Client()
resp = client.models.generate_content(
    model="gemini-2.5-flash-preview-tts",
    contents="Say cheerfully: Have a wonderful day!",
    config=types.GenerateContentConfig(
        response_modalities=["AUDIO"],
        speech_config=types.SpeechConfig(
            voice_config=types.VoiceConfig(
                prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name="Kore")
            )
        ),
    ),
)

pcm = resp.candidates[0].content.parts[0].inline_data.data
save_wav("out.wav", pcm)
```

### 9.3 多说话人 TTS（最多 2 人）
要求：
- 使用 `MultiSpeakerVoiceConfig`
- 每个 speaker 的名字必须与 prompt 中对话标签一致（如 Joe/Jane）。

### 9.4 语音选项与语言
- `voice_name` 支持 30 种预设声音（例如 Zephyr、Puck、Charon、Kore 等）。
- 模型可自动检测输入语言，并支持 24 种语言（以文档列表为准）。

### 9.5 “导演备注”（强烈建议用于高质量配音）
为风格、节奏、口音等关键维度提供可控指令，但避免过度规定以免限制模型。

---

## 10. 音频理解（Audio Understanding）

### 10.1 典型任务
- 描述音频内容（含非语音：鸟鸣、警报等）
- 生成转写（transcript）
- 指定时间段转写
- 统计 token（用于成本评估/分段策略）

### 10.2 Files API（Python）最小模板
```python
from google import genai

client = genai.Client()
myfile = client.files.upload(file="sample.mp3")

resp = client.models.generate_content(
    model="gemini-3-flash-preview",
    contents=["Describe this audio clip", myfile],
)
print(resp.text)
```

### 10.3 关键限制与工程建议
- 支持常见格式：WAV/MP3/AIFF/AAC/OGG/FLAC。
- 音频 token 化：约 32 token/秒（1 分钟约 1920 tokens，数值可能变化）。
- 单个提示内所有音频总时长上限为 9.5 小时；多声道会被合并；音频会被下采样（具体参数以文档为准）。
- 若总请求大小超过 20MB，必须走 Files API。

---

## 11. 端到端示例（组合编排）

### 示例 A：图片生成 → 再理解校验
1) 用 Nano Banana 生成产品图（要求留白、统一光照）。
2) 用图片理解模型做“自检”：确认文字是否清晰、品牌拼写是否正确、是否有违规元素。
3) 若不满足：把生成图作为输入，走图文编辑再次迭代。

### 示例 B：视频生成 → 视频理解生成解说脚本
1) 用 Veo 生成 8 秒镜头（包含对白或 SFX）。
2) 下载并保存（注意保留期限）。
3) 上传视频给视频理解模型生成：分镜脚本 + 时间戳 + 旁白文案（再交给 TTS）。

### 示例 C：音频理解 → 指定时间段转写 → TTS 重配音
1) 上传会议音频，转写全文。
2) 指定时间段做精细转写或摘要。
3) 用 TTS 为摘要生成“播报版音频”。

---

## 12. 合规与风控（必须遵守）

- 确保你对上传的图片/视频/音频拥有必要权利；不得生成侵权、欺骗、骚扰或伤害性内容。
- 生成的图像与视频会带有 SynthID 水印；视频还可能有区域与人物生成策略限制。
- 任何生产系统需实现：超时、重试、失败降级、以及对生成内容的人工抽检/后处理。

---

## 13. 快速参考（Checklist）

- [ ] 选对模型：图像生成（Flash Image / Pro Image Preview）、视频生成（Veo 3.1）、TTS（Gemini 2.5 TTS）、理解（Gemini Flash/Pro）。
- [ ] 选对输入方式：小文件 inline；大文件/复用用 Files API。
- [ ] 正确解析二进制输出：image/audio 走 inline_data 解码；video 走 operation 轮询 + download。
- [ ] 对视频生成：设置 aspectRatio / resolution，并及时下载（避免过期）。
- [ ] 对 TTS：设置 response_modalities=["AUDIO"]；多说话人最多 2；speaker 名称与 prompt 对齐。
- [ ] 对音频理解：必要时 countTokens；长音频按策略分段或走 Files API。

