> ## Documentation Index
> Fetch the complete documentation index at: https://docs.viggle.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 首尾帧生视频

> 给 Viggle H3 一个开场帧和一个结尾帧，它会生成两者之间的动作，并带原生音频。

首尾帧生视频根据你提供的两张图片，生成两者之间的镜头。片段以第一张图片开场、以最后一张图片结束，提示词描述如何从一张过渡到另一张。输出为 5–15 秒、带原生音频的 MP4。

可以用它做转场、前后对比揭示，或在两个已知姿势或机位之间移动。如果只关心开场，请使用[首帧生视频](https://docs.viggle.ai/zh/v1/video/first-frame-to-video.md)。

## 请求内容

以 `multipart/form-data` 调用 `POST /v1/videos`。同时发送首帧和尾帧即选择此模式。

| 参数 | 必填 | 说明 |
| - | - | - |
| `prompt` | 是 | 镜头如何从首帧过渡到尾帧 |
| `quality` | 是 | `low`（更快）或 `high`（保真度更高），价格相同。也可以用 [`ultrafast`](https://docs.viggle.ai/zh/v1/video/generate-video#ultrafast)，最快的档位，单独定价 |
| `first_frame_image` 或 `first_frame_image_url` | 是 | 开场帧，以文件或 URL 发送 |
| `last_frame_image` 或 `last_frame_image_url` | 是 | 结尾帧，以文件或 URL 发送 |
| `aspect_ratio` | 否 | 默认 `16:9`。请设置为与图片一致 |
| `duration_s` | 否 | 5–15 秒，默认 `5` |

每一帧以文件或 URL 发送，不能同时发送；两帧可以混用（例如首帧上传文件、尾帧使用托管 URL）。只有尾帧而没有首帧会被拒绝，返回 `400`。`resolution`、`enhance`、`seed` 和 `watermark` 的用法与其他模式相同，见[通用参数](https://docs.viggle.ai/zh/v1/video/generate-video#common-parameters)。

### 图片限制

两帧遵循相同的规则。

| | 限制 |
| - | - |
| 上传大小 | 每张最大 20 MiB |
| URL 或 `data:` URI 大小 | 每张最大 30 MiB。URL 必须是公开的 `http(s)://` |
| 格式 | JPEG、PNG、WebP、GIF、BMP、TIFF、HEIC |
| 超大图片 | 长边达到 3840 px 及以上，或短边达到 2160 px 及以上的图片，会按原比例缩小到 1920×1080 以内（竖图为 1080×1920） |

帧画面不能与参考图或参考视频同时使用。

## 价格

与所有 Viggle H3 模式相同：按秒数和 `resolution` 计费，开启 `enhance` 时每秒另加 $0.01。两张图片免费。下面的示例（5 秒，768p，开启 enhance）消耗 10 积分（$0.10）。见[单价表](https://docs.viggle.ai/zh/v1/video/generate-video#price)。

## 生成视频

导出 `VIGGLE_API_KEY`，然后直接运行以下任一脚本。为了在没有你自己文件的情况下也能运行，脚本把同一张示例图同时用作首帧和尾帧，生成一个从同一姿势开始并结束的循环。准备好后换成你自己的两个 URL 即可。每个脚本每 5 秒轮询一次，并打印视频 URL。cURL 版本需要 `jq`。

```bash cURL theme={null}
#!/usr/bin/env bash
set -euo pipefail
API="https://apis.viggle.ai/v1"

video_id=$(curl -sS --fail-with-body "$API/videos" \
  -H "Authorization: Bearer $VIGGLE_API_KEY" \
  -F prompt="the character spins around once and ends facing the camera again" \
  -F quality="low" \
  -F first_frame_image_url="https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp" \
  -F last_frame_image_url="https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp" | jq -er '.id')
echo "Submitted $video_id"

for _ in $(seq 1 1440); do
  video=$(curl -sS --fail-with-body "$API/videos/$video_id" \
    -H "Authorization: Bearer $VIGGLE_API_KEY")
  case $(echo "$video" | jq -r '.status') in
    ready) echo "$video" | jq -r '.video_url'; exit 0 ;;
    failed|cancelled) echo "$video" | jq -c '.error' >&2; exit 1 ;;
  esac
  sleep 5
done
echo "Timed out waiting for $video_id" >&2; exit 1
```

```javascript Node.js theme={null}
// Node.js 20+。保存为 first-last-frame.mjs，然后运行：node first-last-frame.mjs
const API = "https://apis.viggle.ai/v1";
const headers = { Authorization: `Bearer ${process.env.VIGGLE_API_KEY}` };

async function call(path, init = {}) {
  const res = await fetch(`${API}${path}`, { ...init, headers });
  const body = await res.json();
  if (!res.ok) throw new Error(`HTTP ${res.status}: ${JSON.stringify(body.error)}`);
  return body;
}

const form = new FormData();
form.append("prompt", "the character spins around once and ends facing the camera again");
form.append("quality", "low");
form.append("first_frame_image_url", "https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp");
form.append("last_frame_image_url", "https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp");
const { id } = await call("/videos", { method: "POST", body: form });
console.log(`Submitted ${id}`);

for (let i = 0; i < 1440; i++) {
  const video = await call(`/videos/${id}`);
  if (video.status === "ready") {
    console.log(video.video_url);
    process.exit(0);
  }
  if (video.status === "failed" || video.status === "cancelled") {
    throw new Error(`${video.status}: ${JSON.stringify(video.error)}`);
  }
  await new Promise((resolve) => setTimeout(resolve, 5000));
}
throw new Error(`Timed out waiting for ${id}`);
```

```python Python theme={null}
import os
import time

import requests

API = "https://apis.viggle.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['VIGGLE_API_KEY']}"}


def check(resp):
    if not resp.ok:
        raise RuntimeError(f"HTTP {resp.status_code}: {resp.text}")
    return resp.json()


# 通过 files= 传字段，requests 会以 multipart/form-data 发送。
video = check(requests.post(f"{API}/videos", headers=HEADERS, timeout=300, files={
    "prompt": (None, "the character spins around once and ends facing the camera again"),
    "quality": (None, "low"),
    "first_frame_image_url": (None, "https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp"),
    "last_frame_image_url": (None, "https://assets.viggle.ai/pub/www/developers/threed-source-image-3f2f6787.webp"),
}))
print("Submitted", video["id"])

for _ in range(1440):
    video = check(requests.get(f"{API}/videos/{video['id']}", headers=HEADERS))
    if video["status"] == "ready":
        print(video["video_url"])
        break
    if video["status"] in ("failed", "cancelled"):
        raise RuntimeError(f"{video['status']}: {video['error']}")
    time.sleep(5)
else:
    raise TimeoutError(f"Timed out waiting for {video['id']}")
```

要上传本地文件，用 `first_frame_image=@first.png` 和 `last_frame_image=@last.png` 替换 URL 字段。

> [!WARNING]
>
> 如果余额不足以支付该任务，请求仍会被接受，随后任务以 `failed` 结束，`error.code: "INSUFFICIENT_CREDITS"`。大批量提交前请先调用 `GET /v1/credits` 查看余额。

## 获取结果

创建请求返回一个 `vid_` ID 和 `status: "queued"`。轮询 `GET /v1/videos/{video_id}`，直到 `status` 为 `ready`，然后下载 `video_url`。

* 链接有效期为一小时，每次读取都会返回新链接。
* 视频在任务结束 24 小时后删除，请复制到你自己的存储中。
* 只有创建该任务的 API 密钥才能读取它。

见[任务生命周期](https://docs.viggle.ai/zh/v1/concepts/task-lifecycle.md)和[错误](https://docs.viggle.ai/zh/v1/production/errors.md)。

## 后续步骤

> [card] [首帧生视频](https://docs.viggle.ai/zh/v1/video/first-frame-to-video.md)
>
> 只固定开场帧，由提示词主导后续内容。

> [card] [参考生视频](https://docs.viggle.ai/zh/v1/video/reference-to-video.md)
>
> 保留主体或风格，而不固定任何一帧。

> [card] [Viggle H3 概览](https://docs.viggle.ai/zh/v1/video/generate-video)
>
> 四种模式、通用参数和价格。

> [card] [创建视频（API 参考）](https://docs.viggle.ai/zh/v1/api-reference/videos/create-a-video.md)
>
> `POST /v1/videos` 的全部字段、限制和错误。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.