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

# 下載影片

> 下載已完成的影片檔案資料

## 簡介

下載影片端點用於取得已完成的影片檔案資料。

<Warning>
  此端點僅支援 Sora 2 模型。其他模型（Veo、豆包 Seedance）在任務成功後，影片 URL 會直接包含在查詢任務回應中，無需額外下載步驟。
</Warning>

## 認證方式

Bearer Token，例如 `Bearer sk-xxxxxxxxxx`

## 查詢參數

<ParamField query="id" type="string" required>
  影片 ID，即查詢任務端點返回的 `task_id`
</ParamField>

## cURL 範例

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/download?id=video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

## 回應範例

```json theme={null}
{
  "success": true,
  "generation_id": "video_69095b4ce0048190893a01510c0c98b0",
  "task_id": "video_69095b4ce0048190893a01510c0c98b0",
  "format": "mp4",
  "size": 15728640,
  "base64": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB...",
  "data_url": "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB..."
}
```

## 回應欄位說明

| 欄位              | 類型      | 說明                                    |
| --------------- | ------- | ------------------------------------- |
| `success`       | boolean | 請求是否成功                                |
| `generation_id` | string  | 生成 ID（與 videoId 相同）                   |
| `task_id`       | string  | 任務 ID                                 |
| `format`        | string  | 影片格式（固定為 `"mp4"`）                     |
| `size`          | number  | 影片檔案大小（位元組）                           |
| `base64`        | string  | Base64 編碼的影片資料                        |
| `data_url`      | string  | Data URL 格式的影片資料，可直接用於前端 `<video>` 標籤 |

## 使用說明

### 前端使用 data\_url

`data_url` 欄位可以直接用於 HTML `<video>` 標籤：

```html theme={null}
<video src="data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDEAAAAIZnJlZQAAB..." controls></video>
```

### 下載儲存檔案

#### JavaScript 範例

```javascript theme={null}
// 從回應中取得 base64 資料
const response = await fetch('https://api.mixroute.ai/v1/video/generations/download?id=video_xxx', {
  headers: {
    'Authorization': 'Bearer sk-xxxxxxxxxx'
  }
});
const data = await response.json();

// 將 base64 轉換為 Blob
const binaryString = atob(data.base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
  bytes[i] = binaryString.charCodeAt(i);
}
const blob = new Blob([bytes], { type: 'video/mp4' });

// 建立下載連結
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'video.mp4';
a.click();
URL.revokeObjectURL(url);
```

#### Python 範例

```python theme={null}
import requests
import base64

def download_video(video_id, api_key):
    """下載影片並儲存為檔案"""
    url = f"https://api.mixroute.ai/v1/video/generations/download?id={video_id}"
    headers = {"Authorization": f"Bearer {api_key}"}

    response = requests.get(url, headers=headers)
    data = response.json()

    if data.get("success"):
        # 解碼 base64 資料
        video_data = base64.b64decode(data["base64"])

        # 儲存為檔案
        with open("video.mp4", "wb") as f:
            f.write(video_data)

        print(f"✅ 影片已儲存：video.mp4（大小：{data['size']} 位元組）")
        return True
    else:
        print("❌ 下載失敗")
        return False
```

## 完整流程範例（Sora 2）

### 1. 提交影片生成任務

```bash theme={null}
curl -X POST "https://api.mixroute.ai/v1/video/generations" \
  -H "Authorization: Bearer sk-xxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "sora-2",
    "prompt": "一隻可愛的小貓在花園裡玩耍",
    "seconds": "4",
    "size": "720x1280"
  }'
```

回應：

```json theme={null}
{
  "task_id": "video_69095b4ce0048190893a01510c0c98b0",
  "status": "submitted",
  "format": "mp4"
}
```

### 2. 查詢任務狀態（輪詢直到成功）

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

當狀態為 `succeeded` 時，繼續下一步。

### 3. 下載影片檔案

```bash theme={null}
curl -X GET "https://api.mixroute.ai/v1/video/generations/download?id=video_69095b4ce0048190893a01510c0c98b0" \
  -H "Authorization: Bearer sk-xxxxxxxxxx"
```

## 注意事項

* 下載端點返回 Base64 編碼的影片資料，適合在前端直接顯示或儲存
* 對於大型檔案，建議使用串流下載或直接 URL 下載
* 影片格式固定為 MP4

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://api.mixroute.ai/v1/video/generations/download?id=video_xxx' \
    --header 'Authorization: Bearer sk-xxxxxxxxxx'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.mixroute.ai/v1/video/generations/download"
  params = {"id": "video_xxx"}
  headers = {"Authorization": "Bearer sk-xxxxxxxxxx"}

  response = requests.get(url, params=params, headers=headers)
  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.mixroute.ai/v1/video/generations/download?id=video_xxx', {
    headers: {
      'Authorization': 'Bearer sk-xxxxxxxxxx'
    }
  });
  const data = await response.json();
  console.log(data);
  ```

  ```php PHP theme={null}
  <?php
  $client = new GuzzleHttp\Client();
  $response = $client->get('https://api.mixroute.ai/v1/video/generations/download', [
      'headers' => [
          'Authorization' => 'Bearer sk-xxxxxxxxxx'
      ],
      'query' => ['id' => 'video_xxx']
  ]);
  echo $response->getBody();
  ```

  ```go Go theme={null}
  package main

  import (
      "net/http"
  )

  func main() {
      req, _ := http.NewRequest("GET", "https://api.mixroute.ai/v1/video/generations/download?id=video_xxx", nil)
      req.Header.Set("Authorization", "Bearer sk-xxxxxxxxxx")
      http.DefaultClient.Do(req)
  }
  ```

  ```java Java theme={null}
  import java.net.http.*;
  import java.net.URI;

  HttpClient client = HttpClient.newHttpClient();
  HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://api.mixroute.ai/v1/video/generations/download?id=video_xxx"))
      .header("Authorization", "Bearer sk-xxxxxxxxxx")
      .GET()
      .build();
  HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
  System.out.println(response.body());
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'

  uri = URI('https://api.mixroute.ai/v1/video/generations/download?id=video_xxx')
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Get.new(uri)
  request['Authorization'] = 'Bearer sk-xxxxxxxxxx'

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json Response theme={null}
  {
    "success": true,
    "generation_id": "video_xxx",
    "task_id": "video_xxx",
    "format": "mp4",
    "size": 15728640,
    "base64": "AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE...",
    "data_url": "data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjMW1wNDE..."
  }
  ```
</ResponseExample>
