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

# 文本生成视频

> 通过 Krea API 使用 ByteDance Seedance、Veo、Kling 和 Hailuo 从文本生成视频，附 REST 与 SDK 示例。

<video autoPlay muted loop playsInline>
  <source src="https://s.krea.ai/docs-text-to-video-new.webm" type="video/webm" />
</video>

![](https://s.krea.ai/docs-text-to-video.webp)

# Text to Video

Generate videos from text. Create cinematic sequences, animations, and visual stories with advanced video generation models.

# Text to Video

Generate videos from text. Create cinematic sequences, animations, and visual stories with advanced video generation models.

如需使用 ByteDance 生成视频，请参阅 [Seedance 文本生成视频 API 快速入门](https://www.krea.ai/docs/cn/developers/seedance.md#generate-a-video)。其中涵盖 Seedance 2.5 和 2.0 端点、身份验证以及任务完成处理。

## 热门模型

Veo 3.1 logo

### [Veo 3.1](https://www.krea.ai/docs/api-reference/video/veo-31.md)

Google's video model with exceptional prompt adherence and cinematic quality.

Kling 2.5 logo

### [Kling 2.5](https://www.krea.ai/docs/api-reference/video/kling-25.md)

Advanced motion control with temporal consistency and realistic physics.

Hailuo 2.3 logo

### [Hailuo 2.3](https://www.krea.ai/docs/api-reference/video/hailuo-23.md)

Fast generation with smooth motion and natural scene transitions.

Wan 2.5 logo

### [Wan 2.5](https://www.krea.ai/docs/api-reference/video/wan-25.md)

High-resolution video synthesis with style control and detail preservation.

***

> [!NOTE]
>
> 视频生成通常比图像生成耗时更长。请根据视频时长和质量设置准备较长的处理时间。

## 步骤 1：生成视频

向 `/generate/video/kling/kling-2.5` 发送 POST 请求，附带你的提示词和视频参数。API 会立即返回一个 job ID。

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// npm install @krea-ai/sdk
import { Krea } from "@krea-ai/sdk";

const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

const job = await krea.video("kling/kling-2.5", {
  prompt: "a majestic eagle soaring over snow-capped mountains at sunrise",
  duration: 5,
  aspect_ratio: "16:9"
});

console.log(`Job ID: ${job.job_id}`);
```

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl -X POST https://api.krea.ai/generate/video/kling/kling-2.5 \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "a majestic eagle soaring over snow-capped mountains at sunrise",
    "duration": 5,
    "aspect_ratio": "16:9"
  }'
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import requests

API_BASE = "https://api.krea.ai"
API_TOKEN = "YOUR_API_TOKEN"

response = requests.post(
    f"{API_BASE}/generate/video/kling/kling-2.5",
    headers={
        "Authorization": f"Bearer {API_TOKEN}",
        "Content-Type": "application/json"
    },
    json={
        "prompt": "a majestic eagle soaring over snow-capped mountains at sunrise",
        "duration": 5,
        "aspect_ratio": "16:9"
    }
)

job = response.json()
print(f"Job ID: {job['job_id']}")
```

```go Go theme={"theme":{"light":"github-light-default","dark":"vesper"}}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

func main() {
    apiBase := "https://api.krea.ai"
    apiToken := "YOUR_API_TOKEN"

    payload := map[string]interface{}{
        "prompt": "a majestic eagle soaring over snow-capped mountains at sunrise",
        "duration": 5,
        "aspect_ratio": "16:9",
    }

    jsonData, _ := json.Marshal(payload)
    req, _ := http.NewRequest("POST", apiBase+"/generate/video/kling/kling-2.5", bytes.NewBuffer(jsonData))
    req.Header.Set("Authorization", "Bearer "+apiToken)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    var job map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&job)
    fmt.Printf("Job ID: %s\n", job["job_id"])
}
```

> [!NOTE]
>
> **替换为你的 API Token**
>
> 要替换上述示例中的 YOUR\_API\_TOKEN 占位符，你需要在 [krea.ai/settings/api-tokens](https://www.krea.ai/settings/api-tokens) 生成一个 API token。如果需要帮助，请参考 [API Keys & Billing](https://www.krea.ai/docs/developers/api-keys-and-billing.md) 页面上的说明。

**示例响应**

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "scheduled",
  "created_at": "2025-01-15T10:30:00.000Z",
  "estimated_time": "60-120 seconds"
}
```

***

## 步骤 2：轮询结果

视频生成比图像生成耗时更长。每 5 秒轮询一次 `/jobs/{job_id}` 以检查进度。

> [!NOTE]
>
> **Webhook 可用！**
>
> 设置 webhook，可在任务完成时收到通知。参见 [Webhooks 指南](https://www.krea.ai/docs/developers/webhooks.md) 开始使用。

```javascript Node.js theme={"theme":{"light":"github-light-default","dark":"vesper"}}
// npm install @krea-ai/sdk
import { Krea } from "@krea-ai/sdk";

const krea = new Krea({ apiKey: process.env.KREA_API_KEY });

async function waitForVideo(jobId) {
  const completed = await krea.jobs.wait(jobId, { intervalMs: 5000 });
  return completed.result.urls[0];
}

const videoUrl = await waitForVideo(job.job_id);
console.log(`Video ready: ${videoUrl}`);
```

```bash cURL theme={"theme":{"light":"github-light-default","dark":"vesper"}}
curl -X GET https://api.krea.ai/jobs/YOUR_JOB_ID \
  -H "Authorization: Bearer YOUR_API_TOKEN"
```

```python Python theme={"theme":{"light":"github-light-default","dark":"vesper"}}
import time

def wait_for_video(job_id):
    while True:
        response = requests.get(
            f"{API_BASE}/jobs/{job_id}",
            headers={"Authorization": f"Bearer {API_TOKEN}"}
        )
        job = response.json()

        if job["status"] == "completed":
            return job["result"]["urls"][0]
        if job["status"] in ("failed", "cancelled"):
            raise Exception(f"Job failed: {job['status']}")

        # Show progress if available
        if "progress" in job:
            print(f"Progress: {job['progress']}%")
        else:
            print(f"Status: {job['status']}")

        time.sleep(5)

video_url = wait_for_video(job["job_id"])
print(f"Video ready: {video_url}")
```

```go Go theme={"theme":{"light":"github-light-default","dark":"vesper"}}
func waitForVideo(jobID string) (string, error) {
    for {
        req, _ := http.NewRequest("GET", apiBase+"/jobs/"+jobID, nil)
        req.Header.Set("Authorization", "Bearer "+apiToken)

        resp, _ := client.Do(req)
        var job map[string]interface{}
        json.NewDecoder(resp.Body).Decode(&job)
        resp.Body.Close()

        switch job["status"] {
        case "completed":
            result := job["result"].(map[string]interface{})
            urls := result["urls"].([]interface{})
            return urls[0].(string), nil
        case "failed", "cancelled":
            return "", fmt.Errorf("job failed: %s", job["status"])
        }

        // Show progress if available
        if progress, ok := job["progress"]; ok {
            fmt.Printf("Progress: %.0f%%\n", progress)
        } else {
            fmt.Printf("Status: %s\n", job["status"])
        }

        time.Sleep(5 * time.Second)
    }
}
```

**示例完成响应**

```json theme={"theme":{"light":"github-light-default","dark":"vesper"}}
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "created_at": "2025-01-15T10:30:00.000Z",
  "completed_at": "2025-01-15T10:31:45.000Z",
  "result": {
    "urls": ["https://gen.krea.ai/videos/your-video.mp4"]
  }
}
```

> [!NOTE]
>
> **Webhook 可用！**
>
> 设置 webhook，可在任务完成时收到通知。参见 [Webhooks 指南](https://www.krea.ai/docs/developers/webhooks.md) 开始使用。

***

## 常用参数

> [!TIP]
>
> 要查看所有模型的详细参数列表，请访问 [Model APIs](https://www.krea.ai/docs/api-reference/introduction.md) 页面。

| 参数 | 类型 | 说明 |
| - | - | - |
| `prompt` | string | 视频内容的详细描述 |
| `duration` | number | 视频时长（秒）。可选值取决于具体模型。 |
| `aspect_ratio` | string | 视频宽高比，例如 `16:9`、`9:16` 或 `1:1` |
| `start_image` | string | 可选，图像生成视频模型的源图像 URL |
| `end_image` | string | 可选，支持的模型的结束帧 URL |
| `mode` | string | 可选，部分模型公开的质量模式 |
| `model` | string | 要使用的视频生成模型 |

> [!TIP]
>
> **获得更好视频的提示词技巧：**
>
> * 具体描述运动和相机运动
> * 描述场景、光照和氛围
> * 提及时间感（例如"缓慢平移"、"快速拉近"）
> * 加入风格参考（例如"电影感"、"纪录片风格"）

> [!WARNING]
>
> 视频生成的费用比图像生成更高。请查看 [API Keys & Billing](https://www.krea.ai/docs/developers/api-keys-and-billing.md)，了解各模型定价和如何为 API 余额充值。


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