如需了解视频理解,请参阅视频理解指南。
Veo 3.1 是一款用于生成 8 秒视频(720p、1080p 或 4k)的模型,可原生生成音频。您可以使用 Gemini API 以编程方式访问此模型。如需详细了解可用的 Veo 模型变体,请参阅模型版本部分。
Veo 3.1 擅长各种视觉和电影风格,并引入了多项新功能:
- 竖屏视频:在横屏 (
16:9) 和竖屏 (9:16) 视频之间进行选择。 - 视频扩展:扩展之前使用 Veo 生成的视频。
- 特定于帧的生成:通过指定第一帧和最后一帧来生成视频。
- 基于图片的指导:最多可使用三张参考图片来指导生成视频的内容。
如需详细了解如何编写有效的文本提示来生成视频,请参阅 Veo 提示指南
文生视频
以下示例展示了如何生成包含对话、电影级写实风格或创意动画的视频:
对话和音效
Python
import time
from google import genai
from google.genai import types
client = genai.Client()
prompt = """A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'"""
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="dialogue_example.mp4")
print("Generated video saved to dialogue_example.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = `A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'`;
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the generated video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "dialogue_example.mp4",
});
console.log(`Generated video saved to dialogue_example.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.
A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'`
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil,
nil,
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the generated video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "dialogue_example.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;
Client client = new Client();
String prompt =
"A close up of two people staring at a cryptic drawing on a wall, torchlight flickering.\n"
+ "A man murmurs, 'This must be it. That's the secret code.' The woman looks at him and whispering excitedly, 'What did you find?'";
GenerateVideosOperation operation =
client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);
// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
System.out.println("Waiting for video generation to complete...");
Thread.sleep(10000);
operation = client.operations.getVideosOperation(operation, null);
}
// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "dialogue_example.mp4", null);
System.out.println("Generated video saved to dialogue_example.mp4");
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A close up of two people staring at a cryptic drawing on a wall, torchlight flickering. A man murmurs, \"This must be it. That'\''s the secret code.\" The woman looks at him and whispering excitedly, \"What did you find?\""
}
]
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o dialogue_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 5 seconds before checking again.
sleep 10
done
电影级写实风格
Python
import time
from google import genai
from google.genai import types
client = genai.Client()
prompt = """Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
The convertible accelerates fast and the engine roars loudly."""
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="realism_example.mp4")
print("Generated video saved to realism_example.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = `Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
The convertible accelerates fast and the engine roars loudly.`;
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the generated video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "realism_example.mp4",
});
console.log(`Generated video saved to realism_example.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.
The convertible accelerates fast and the engine roars loudly.`
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil,
nil,
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the generated video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "realism_example.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;
Client client = new Client();
String prompt =
"Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below.\n"
+ "The convertible accelerates fast and the engine roars loudly.";
GenerateVideosOperation operation =
client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);
// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
System.out.println("Waiting for video generation to complete...");
Thread.sleep(10000);
operation = client.operations.getVideosOperation(operation, null);
}
// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "realism_example.mp4", null);
System.out.println("Generated video saved to realism_example.mp4");
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "Drone shot following a classic red convertible driven by a man along a winding coastal road at sunset, waves crashing against the rocks below. The convertible accelerates fast and the engine roars loudly."
}
]
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o realism_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 5 seconds before checking again.
sleep 10
done
创意动画
Python
import time
from google import genai
client = genai.Client()
prompt = "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet."
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="style_example.mp4")
print("Generated video saved to style_example.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.";
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the generated video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "style_example.mp4",
});
console.log(`Generated video saved to style_example.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.`
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil,
nil,
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the generated video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "style_example.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;
Client client = new Client();
String prompt =
"A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet.";
GenerateVideosOperation operation =
client.models.generateVideos("veo-3.1-generate-preview", prompt, null, null);
// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
System.out.println("Waiting for video generation to complete...");
Thread.sleep(10000);
operation = client.operations.getVideosOperation(operation, null);
}
// Download the generated video.
GeneratedVideo generatedVideo = operation.response().get().generatedVideos().get().get(0);
client.files.download(generatedVideo, "style_example.mp4", null);
System.out.println("Generated video saved to style_example.mp4");
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A whimsical stop-motion animation of a tiny robot tending to a garden of glowing mushrooms on a miniature planet."
}
]
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o style_example.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 5 seconds before checking again.
sleep 10
done
控制宽高比
Veo 3.1 可让您制作横屏(16:9,默认设置)或竖屏 (9:16) 视频。您可以使用 aspect_ratio 参数告知模型您想要哪种:
Python
import time
from google import genai
from google.genai import types
client = genai.Client()
prompt = """A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video."""
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
config=types.GenerateVideosConfig(
aspect_ratio="9:16",
),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="pizza_making.mp4")
print("Generated video saved to pizza_making.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = `A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video.`;
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
config: {
aspectRatio: "9:16",
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the generated video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "pizza_making.mp4",
});
console.log(`Generated video saved to pizza_making.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video.`
videoConfig := &genai.GenerateVideosConfig{
AspectRatio: "9:16",
}
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil,
videoConfig,
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the generated video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "pizza_making.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A montage of pizza making: a chef tossing and flattening the floury dough, ladling rich red tomato sauce in a spiral, sprinkling mozzarella cheese and pepperoni, and a final shot of the bubbling golden-brown pizza, upbeat electronic music with a rhythmical beat is playing, high energy professional video."
}
],
"parameters": {
"aspectRatio": "9:16"
}
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o pizza_making.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 5 seconds before checking again.
sleep 10
done
控制分辨率
Veo 3.1 还可以直接生成 720p、1080p 或 4k 视频(Veo 3.1 Lite 不支持 4k)。
请注意,分辨率越高,延迟时间就越长。4k 视频的价格也更高(请参阅价格)。
视频扩展程序也仅限于 720p 视频。
Python
import time
from google import genai
from google.genai import types
client = genai.Client()
prompt = """A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon."""
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
config=types.GenerateVideosConfig(
resolution="4k",
),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the generated video.
generated_video = operation.response.generated_videos[0]
client.files.download(file=generated_video.video, destination="4k_grand_canyon.mp4")
print("Generated video saved to 4k_grand_canyon.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.`;
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
config: {
resolution: "4k",
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the generated video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "4k_grand_canyon.mp4",
});
console.log(`Generated video saved to 4k_grand_canyon.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon's colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon.`
videoConfig := &genai.GenerateVideosConfig{
Resolution: "4k",
}
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil,
videoConfig,
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the generated video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "4k_grand_canyon.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A stunning drone view of the Grand Canyon during a flamboyant sunset that highlights the canyon'\''s colors. The drone slowly flies towards the sun then accelerates, dives and flies inside the canyon."
}
],
"parameters": {
"resolution": "4k"
}
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o 4k_grand_canyon.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 5 seconds before checking again.
sleep 10
done
图生视频
以下代码演示了如何使用 Gemini 3.1 Flash Image(又称 Nano Banana 2)生成图片,然后将该图片用作起始帧,通过 Veo 3.1 生成视频。
Python
import time
from google import genai
client = genai.Client()
prompt = "Panning wide shot of a calico kitten sleeping in the sunshine"
# Step 1: Generate an image with Nano Banana 2.
image = client.models.generate_content(
model="gemini-3.1-flash-image-preview",
contents=prompt,
config={"response_modalities":['IMAGE']}
)
# Step 2: Generate video with Veo 3.1 using the image.
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
image=image.parts[0].as_image(),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3_with_image_input.mp4")
print("Generated video saved to veo3_with_image_input.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "Panning wide shot of a calico kitten sleeping in the sunshine";
// Step 1: Generate an image with Nano Banana 2.
const imageResponse = await ai.models.generateContent({
model: "gemini-3.1-flash-image-preview",
prompt: prompt,
});
// Step 2: Generate video with Veo 3.1 using the image.
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
image: {
imageBytes: imageResponse.generatedImages[0].image.imageBytes,
mimeType: "image/png",
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "veo3_with_image_input.mp4",
});
console.log(`Generated video saved to veo3_with_image_input.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := "Panning wide shot of a calico kitten sleeping in the sunshine"
// Step 1: Generate an image with Nano Banana 2.
imageResponse, err := client.Models.GenerateContent(
ctx,
"gemini-3.1-flash-image-preview",
prompt,
nil, // GenerateImagesConfig
)
if err != nil {
log.Fatal(err)
}
// Step 2: Generate video with Veo 3.1 using the image.
operation, err := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
imageResponse.GeneratedImages[0].Image,
nil, // GenerateVideosConfig
)
if err != nil {
log.Fatal(err)
}
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "veo3_with_image_input.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
Java
import com.google.genai.Client;
import com.google.genai.types.Blob;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.GenerateVideosOperation;
import com.google.genai.types.GeneratedVideo;
import com.google.genai.types.Image;
Client client = new Client();
String prompt = "Panning wide shot of a calico kitten sleeping in the sunshine";
// Step 1: Generate an image with Nano Banana 2.
GenerateContentResponse imageResponse =
client.models.generateContent(
"gemini-3.1-flash-image-preview",
prompt,
GenerateContentConfig.builder().responseModalities("IMAGE").build());
Blob inlineData = imageResponse.parts().get(0).inlineData().get();
Image image =
Image.builder()
.imageBytes(inlineData.data().get())
.mimeType(inlineData.mimeType().orElse("image/png"))
.build();
// Step 2: Generate video with Veo 3.1 using the image.
GenerateVideosOperation operation =
client.models.generateVideos("veo-3.1-generate-preview", prompt, image, null);
// Poll the operation status until the video is ready.
while (!operation.done().orElse(false)) {
System.out.println("Waiting for video generation to complete...");
Thread.sleep(10000);
operation = client.operations.getVideosOperation(operation, null);
}
// Download the video.
GeneratedVideo video = operation.response().get().generatedVideos().get().get(0);
client.files.download(video, "veo3_with_image_input.mp4", null);
System.out.println("Generated video saved to veo3_with_image_input.mp4");
使用参考图片
Veo 3.1 现在最多可接受 3 张参考图片,用于指导生成的视频内容。提供人物、角色或产品的图片,以便在输出视频中保留主体的外观。
例如,使用以下三张由 Nano Banana 生成的图片作为参考,并搭配精心撰写的提示,即可生成以下视频:
`dress_image` |
`woman_image` |
`glasses_image` |
|---|---|---|
|
|
|
Python
import time
from google import genai
client = genai.Client()
prompt = "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy."
dress_reference = types.VideoGenerationReferenceImage(
image=dress_image, # Generated separately with Nano Banana
reference_type="asset"
)
sunglasses_reference = types.VideoGenerationReferenceImage(
image=glasses_image, # Generated separately with Nano Banana
reference_type="asset"
)
woman_reference = types.VideoGenerationReferenceImage(
image=woman_image, # Generated separately with Nano Banana
reference_type="asset"
)
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
config=types.GenerateVideosConfig(
reference_images=[dress_reference, glasses_reference, woman_reference],
),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_with_reference_images.mp4")
print("Generated video saved to veo3.1_with_reference_images.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.";
// dressImage, glassesImage, womanImage generated separately with Nano Banana
// and available as objects like { imageBytes: "...", mimeType: "image/png" }
const dressReference = {
image: dressImage,
referenceType: "asset",
};
const sunglassesReference = {
image: glassesImage,
referenceType: "asset",
};
const womanReference = {
image: womanImage,
referenceType: "asset",
};
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
config: {
referenceImages: [
dressReference,
sunglassesReference,
womanReference,
],
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...");
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "veo3.1_with_reference_images.mp4",
});
console.log(`Generated video saved to veo3.1_with_reference_images.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress's long train glides and floats gracefully on the water's surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.`
// dressImage, glassesImage, womanImage generated separately with Nano Banana
// and available as *genai.Image objects.
var dressImage, glassesImage, womanImage *genai.Image
dressReference := &genai.VideoGenerationReferenceImage{
Image: dressImage,
ReferenceType: "asset",
}
sunglassesReference := &genai.VideoGenerationReferenceImage{
Image: glassesImage,
ReferenceType: "asset",
}
womanReference := &genai.VideoGenerationReferenceImage{
Image: womanImage,
ReferenceType: "asset",
}
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil, // image
&genai.GenerateVideosConfig{
ReferenceImages: []*genai.VideoGenerationReferenceImage{
dressReference,
sunglassesReference,
womanReference,
},
},
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "veo3.1_with_reference_images.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
REST
# Note: This script uses jq to parse the JSON response.
# It assumes dress_image_base64, glasses_image_base64, and woman_image_base64
# contain base64-encoded image data.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "The video opens with a medium, eye-level shot of a beautiful woman with dark hair and warm brown eyes. She wears a magnificent, high-fashion flamingo dress with layers of pink and fuchsia feathers, complemented by whimsical pink, heart-shaped sunglasses. She walks with serene confidence through the crystal-clear, shallow turquoise water of a sun-drenched lagoon. The camera slowly pulls back to a medium-wide shot, revealing the breathtaking scene as the dress'\''s long train glides and floats gracefully on the water'\''s surface behind her. The cinematic, dreamlike atmosphere is enhanced by the vibrant colors of the dress against the serene, minimalist landscape, capturing a moment of pure elegance and high-fashion fantasy.",
"referenceImages": [
{
"image": {"inlineData": {"mimeType": "image/png", "data": "'"$dress_image_base64"'"}},
"referenceType": "asset"
},
{
"image": {"inlineData": {"mimeType": "image/png", "data": "'"$glasses_image_base64"'"}},
"referenceType": "asset"
},
{
"image": {"inlineData": {"mimeType": "image/png", "data": "'"$woman_image_base64"'"}},
"referenceType": "asset"
}
]
}],
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o veo3.1_with_reference_images.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 10 seconds before checking again.
sleep 10
done
使用第一帧和最后一帧
借助 Veo 3.1,您可以使用插值或指定视频的第一帧和最后一帧来创建视频。如需了解如何编写有效的文本提示来生成视频,请参阅 Veo 提示指南。
Python
import time
from google import genai
client = genai.Client()
prompt = "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence."
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt=prompt,
image=first_image, # The starting frame is passed as a primary input
config=types.GenerateVideosConfig(
last_frame=last_image # The ending frame is passed as a generation constraint in the config
),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_with_interpolation.mp4")
print("Generated video saved to veo3.1_with_interpolation.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.";
// firstImage and lastImage generated separately with Nano Banana
// and available as objects like { imageBytes: "...", mimeType: "image/png" }
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: prompt,
image: firstImage, // The starting frame is passed as a primary input
config: {
lastFrame: lastImage, // The ending frame is passed as a generation constraint in the config
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "veo3.1_with_interpolation.mp4",
});
console.log(`Generated video saved to veo3.1_with_interpolation.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.`
// firstImage and lastImage generated separately with Nano Banana
// and available as *genai.Image objects.
var firstImage, lastImage *genai.Image
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
firstImage, // The starting frame is passed as a primary input
&genai.GenerateVideosConfig{
LastFrame: lastImage, // The ending frame is passed as a generation constraint in the config
},
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "veo3.1_with_interpolation.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
REST
# Note: This script uses jq to parse the JSON response.
# It assumes first_image_base64 and last_image_base64
# contain base64-encoded image data.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
# The starting frame is passed as a primary input
# The ending frame is passed as a generation constraint in the config
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A cinematic, haunting video. A ghostly woman with long white hair and a flowing dress swings gently on a rope swing beneath a massive, gnarled tree in a foggy, moonlit clearing. The fog thickens and swirls around her, and she slowly fades away, vanishing completely. The empty swing is left swaying rhythmically on its own in the eerie silence.",
"image": {"inlineData": {"mimeType": "image/png", "data": "'"$first_image_base64"'"}},
"lastFrame": {"inlineData": {"mimeType": "image/png", "data": "'"$last_image_base64"'"}}
}],
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o veo3.1_with_interpolation.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 10 seconds before checking again.
sleep 10
done
`first_image` |
`last_image` |
veo3.1_with_interpolation.mp4 |
|---|---|---|
|
|
|
延长 Veo 视频
使用 Veo 3.1 可将之前使用 Veo 生成的视频延长 7 秒,最多可延长 20 次。
输入视频限制:
- Veo 生成的视频时长上限为 141 秒。
- Gemini API 仅支持对 Veo 生成的视频进行视频扩展。
- 视频应来自上一代,例如
operation.response.generated_videos[0].video - 视频会存储 2 天,但如果视频被引用以进行扩展,其 2 天存储计时器会重置。您只能扩展过去两天内生成或引用的视频。
- 输入视频应具有特定的时长、宽高比和尺寸:
- 宽高比:9:16 或 16:9
- 分辨率:720p
- 视频时长:不超过 141 秒
扩展功能的输出是一个视频,其中结合了用户输入的视频和生成的扩展视频,视频时长最长可达 148 秒。
此示例采用 Veo 生成的视频(此处显示了其原始提示),并使用 video 参数和新提示对其进行扩展:
| 提示 | 输出:butterfly_video |
|---|---|
| 一只折纸蝴蝶扇动翅膀,飞出法式双扇玻璃门,进入花园。 |
|
Python
import time
from google import genai
client = genai.Client()
prompt = "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower."
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
video=operation.response.generated_videos[0].video, # This must be a video from a previous generation
prompt=prompt,
config=types.GenerateVideosConfig(
number_of_videos=1,
resolution="720p"
),
)
# Poll the operation status until the video is ready.
while not operation.done:
print("Waiting for video generation to complete...")
time.sleep(10)
operation = client.operations.get(operation)
# Download the video.
video = operation.response.generated_videos[0]
client.files.download(file=video.video, destination="veo3.1_extension.mp4")
print("Generated video saved to veo3.1_extension.mp4")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
const prompt = "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.";
// butterflyVideo must be a video from a previous generation
// available as an object like { videoBytes: "...", mimeType: "video/mp4" }
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
video: butterflyVideo,
prompt: prompt,
config: {
numberOfVideos: 1,
resolution: "720p",
},
});
// Poll the operation status until the video is ready.
while (!operation.done) {
console.log("Waiting for video generation to complete...")
await new Promise((resolve) => setTimeout(resolve, 10000));
operation = await ai.operations.getVideosOperation({
operation: operation,
});
}
// Download the video.
ai.files.download({
file: operation.response.generatedVideos[0].video,
downloadPath: "veo3.1_extension.mp4",
});
console.log(`Generated video saved to veo3.1_extension.mp4`);
Go
package main
import (
"context"
"log"
"os"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
prompt := `Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.`
// butterflyVideo must be a video from a previous generation
// available as a *genai.Video object.
var butterflyVideo *genai.Video
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
prompt,
nil, // image
butterflyVideo,
&genai.GenerateVideosConfig{
NumberOfVideos: 1,
Resolution: "720p",
},
)
// Poll the operation status until the video is ready.
for !operation.Done {
log.Println("Waiting for video generation to complete...")
time.Sleep(10 * time.Second)
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Download the video.
video := operation.Response.GeneratedVideos[0]
client.Files.Download(ctx, video.Video, nil)
fname := "veo3.1_extension.mp4"
_ = os.WriteFile(fname, video.Video.VideoBytes, 0644)
log.Printf("Generated video saved to %s\n", fname)
}
REST
# Note: This script uses jq to parse the JSON response.
# It assumes butterfly_video_base64 contains base64-encoded
# video data from a previous generation.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "Track the butterfly into the garden as it lands on an orange origami flower. A fluffy white puppy runs up and gently pats the flower.",
"video": {"inlineData": {"mimeType": "video/mp4", "data": "'"$butterfly_video_base64"'"}}
}],
"parameters": {
"numberOfVideos": 1,
"resolution": "720p"
}
}' | jq -r .name)
# Poll the operation status until the video is ready
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Extract the download URI from the final response.
video_uri=$(echo "${status_response}" | jq -r '.response.generateVideoResponse.generatedSamples[0].video.uri')
echo "Downloading video from: ${video_uri}"
# Download the video using the URI and API key and follow redirects.
curl -L -o veo3.1_extension.mp4 -H "x-goog-api-key: $GEMINI_API_KEY" "${video_uri}"
break
fi
# Wait for 10 seconds before checking again.
sleep 10
done
如需了解如何编写有效的文本提示来生成视频,请参阅 Veo 提示指南。
处理异步操作
视频生成是一项计算密集型任务。当您向 API 发送请求时,它会启动一个长时间运行的作业,并立即返回一个 operation 对象。然后,您必须轮询,直到视频准备就绪(done 状态为 true)。
此过程的核心是轮询循环,它会定期检查作业的状态。
Python
import time
from google import genai
from google.genai import types
client = genai.Client()
# After starting the job, you get an operation object.
operation = client.models.generate_videos(
model="veo-3.1-generate-preview",
prompt="A cinematic shot of a majestic lion in the savannah.",
)
# Alternatively, you can use operation.name to get the operation.
operation = types.GenerateVideosOperation(name=operation.name)
# This loop checks the job status every 10 seconds.
while not operation.done:
time.sleep(10)
# Refresh the operation object to get the latest status.
operation = client.operations.get(operation)
# Once done, the result is in operation.response.
# ... process and download your video ...
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
// After starting the job, you get an operation object.
let operation = await ai.models.generateVideos({
model: "veo-3.1-generate-preview",
prompt: "A cinematic shot of a majestic lion in the savannah.",
});
// Alternatively, you can use operation.name to get the operation.
// operation = types.GenerateVideosOperation(name=operation.name)
// This loop checks the job status every 10 seconds.
while (!operation.done) {
await new Promise((resolve) => setTimeout(resolve, 1000));
// Refresh the operation object to get the latest status.
operation = await ai.operations.getVideosOperation({ operation });
}
// Once done, the result is in operation.response.
// ... process and download your video ...
Go
package main
import (
"context"
"log"
"time"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// After starting the job, you get an operation object.
operation, _ := client.Models.GenerateVideos(
ctx,
"veo-3.1-generate-preview",
"A cinematic shot of a majestic lion in the savannah.",
nil,
nil,
)
// This loop checks the job status every 10 seconds.
for !operation.Done {
time.Sleep(10 * time.Second)
// Refresh the operation object to get the latest status.
operation, _ = client.Operations.GetVideosOperation(ctx, operation, nil)
}
// Once done, the result is in operation.Response.
// ... process and download your video ...
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateVideosOperation;
Client client = new Client();
// After starting the job, you get an operation object.
GenerateVideosOperation operation =
client.models.generateVideos(
"veo-3.1-generate-preview",
"A cinematic shot of a majestic lion in the savannah.",
null,
null);
// Alternatively, you can use operation.name to construct the operation.
operation = GenerateVideosOperation.builder().name(operation.name().get()).build();
// This loop checks the job status every 10 seconds.
while (!operation.done().orElse(false)) {
Thread.sleep(10000);
// Refresh the operation object to get the latest status.
operation = client.operations.getVideosOperation(operation, null);
}
// Once done, the result is in operation.response().
// ... process and download your video ...
REST
# Note: This script uses jq to parse the JSON response.
# GEMINI API Base URL
BASE_URL="https://generativelanguage.googleapis.com/v1beta"
# Send request to generate video and capture the operation name into a variable.
operation_name=$(curl -s "${BASE_URL}/models/veo-3.1-generate-preview:predictLongRunning" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H "Content-Type: application/json" \
-X "POST" \
-d '{
"instances": [{
"prompt": "A cinematic shot of a majestic lion in the savannah."
}
]
}' | jq -r .name)
# This loop checks the job status every 10 seconds.
while true; do
# Get the full JSON status and store it in a variable.
status_response=$(curl -s -H "x-goog-api-key: $GEMINI_API_KEY" "${BASE_URL}/${operation_name}")
# Check the "done" field from the JSON stored in the variable.
is_done=$(echo "${status_response}" | jq .done)
if [ "${is_done}" = "true" ]; then
# Once done, the result is in status_response.
# ... process and download your video ...
echo "Video generation complete."
break
fi
# Wait for 10 seconds before checking again.
echo "Waiting for video generation to complete..."
sleep 10
done
Veo API 参数和规范
您可以在 API 请求中设置以下参数,以控制视频生成过程。
| 参数 | Veo 3.1 和 Veo 3.1 Fast | Veo 3.1 Lite | Veo 3 和 Veo 3 Fast |
|---|---|---|---|
| 实例 | |||
prompt:视频的文字说明。支持音频提示。 |
string |
string |
string |
image:要为其制作动画的初始图片。 |
Image 对象 |
Image 对象 |
Image 对象 |
lastFrame:插值视频过渡到的最终图片。必须与 image 参数结合使用。 |
Image 对象 |
Image 对象 |
Image 对象 |
referenceImages:最多三张图片,用作风格和内容参考。 |
VideoGenerationReferenceImage 对象 |
n/a 对象 |
无 |
video:要用于视频附加信息的视频。 |
上一代 Video 对象 |
无 | 无 |
| 参数 | |||
aspectRatio:视频的宽高比。 |
"16:9"(默认)、"9:16" |
"16:9"(默认)、"9:16" |
"16:9"(默认)、"9:16" |
durationSeconds:生成的视频的时长。 |
"4","6","8"。使用扩展程序、参考图片或 1080p 和 4k 分辨率时,必须为“8” |
"4","6","8"。使用参考图片或 1080p 时,必须为“8” |
"4","6","8"。使用扩展程序、参考图片或 1080p 和 4k 分辨率时,必须为“8” |
personGeneration:控制人物生成。 (如需了解地区限制,请参阅限制) |
文生视频和扩展:仅限 "allow_all"图生视频、插值和参考图片:仅限 "allow_adult"
|
文生视频:仅限 "allow_all"图生视频、插值和参考图片:仅限 "allow_adult"
|
文生视频:仅限 "allow_all"图生视频:仅限 "allow_adult"
|
resolution:视频的分辨率。 |
"720p"(默认)、"1080p"(仅支持 8 秒时长)、"4k"(仅支持 8 秒时长)"720p" 仅适用于扩展程序
|
"720p"(默认)、"1080p"(仅支持 8 秒时长) |
"720p"(默认)、"1080p"(仅支持 8 秒时长)、"4k"(仅支持 8 秒时长)"720p" 仅适用于扩展程序
|
请注意,seed 参数也适用于 Veo 3 模型。
它不能保证确定性,但可以略微提高确定性。
模型特征
| 功能 | Veo 3.1 和 Veo 3.1 Fast | Veo 3.1 Lite | Veo 3 和 Veo 3 Fast |
|---|---|---|---|
| 音频: 在生成视频的同时生成音频。 |
✔️ 始终开启 | ✔️ 始终开启 | ✔️ 始终开启 |
| 输入模态: 用于生成的输入类型。 |
文生视频、图生视频、视频生视频 | 文生视频、图生视频 | 文生视频、图生视频 |
| 分辨率: 视频的输出分辨率。 |
720p、1080p(仅限 8 秒时长)、4k(仅限 8 秒时长) 使用视频扩展功能时,仅支持 720p。 |
720p、1080p(仅限 8 秒时长) |
720p 和 1080p(仅限 16:9) |
| 帧速率: 视频的输出帧速率。 |
24 帧/秒 | 24 帧/秒 | 24 帧/秒 |
| 视频时长: 生成的视频的时长。 |
8 秒、6 秒、4 秒 仅在 1080p 或 4k 或使用参考图片时支持 8 秒 |
8 秒、6 秒、4 秒 仅在 1080p 或使用参考图片时为 8 秒 |
8 秒 |
| 每次请求生成的视频数: 每次请求生成的视频数量。 |
1 | 1 | 1 |
| 状态: 模型可用性 |
预览 | 预览 | 稳定 |
限制
- 多视频提示:目前不支持跨多个视频进行引用或推理。尝试多视频提示可能会导致模型性能下降或输出意外结果。
- 语言支持:完全支持英语 (EN),但其他语言尚未经过评估,因此可能可以使用,但结果可能会有所不同。
- 请求延迟时间:最短:11 秒;最长:6 分钟(高峰时段)。
- 地区限制:在欧盟、英国、瑞士、中东和北非地区,
allow_adult是personGeneration唯一允许的值。 - 视频保留:生成的视频会在服务器上存储 2 天,之后会被移除。如需保存本地副本,您必须在视频生成后的 2 天内下载视频。扩展后的视频会被视为新生成的视频。
- 水印:Veo 制作的视频会使用 SynthID 添加水印,SynthID 是我们用于为 AI 生成的内容添加水印和进行识别的工具。可以使用 SynthID 验证平台验证视频。
- 安全性:生成的视频会通过安全过滤器和记忆检查流程,这有助于降低隐私、版权和偏见风险。
- 音频错误:Veo 3.1 有时会因安全过滤器或音频处理问题而阻止视频生成。如果视频被阻止生成,系统不会向您扣款。
Veo 提示指南
本部分包含您可以使用 Veo 创建的视频示例,并展示了如何修改提示以产生不同的结果。
安全过滤器
Veo 在 Gemini 中应用了安全过滤器,以帮助确保生成的视频和上传的照片不包含冒犯性内容。 违反我们的条款和准则的提示会被屏蔽。
提示撰写的基础知识
好的提示应具有描述性且清晰。若要充分利用 Veo,请先确定核心创意,然后通过添加关键字和修饰语来优化创意,并在提示中融入视频专用术语。
提示中应包含以下元素:
- 主体:您希望在视频中呈现的对象、人物、动物或场景,例如城市景观、自然风光、车辆或小狗。
- 动作:主体正在做的事情(例如,走路、跑步或转头)。
- 风格:使用特定的电影风格关键字(例如科幻、恐怖片、黑白电影)或动画风格(例如卡通)指定创意方向。
- 相机定位和运动:[可选] 使用航拍视图、平视、俯拍、推轨镜头或仰拍等术语控制相机的位置和移动。
- 构图:[可选] 镜头的取景方式,例如广角镜头、特写镜头、单人镜头或双人镜头。
- 焦点和镜头效果:[可选] 使用浅焦点、深焦点、柔焦、微距镜头和广角镜头等术语来实现特定的视觉效果。
- 氛围:[可选] 颜色和光线对场景的影响,例如蓝色调、夜晚或暖色调。
有关编写提示的更多技巧
- 使用描述性语言:使用形容词和副词,为 Veo 描绘清晰的画面。
- 增强面部细节:指定面部细节作为照片的焦点,例如在提示中使用 portrait 一词。
如需了解更全面的提示策略,请参阅提示设计简介。
提示输入音频
您可以向 Veo 提供音效、环境噪音和对话方面的提示。 该模型会捕捉这些提示的细微差别,以生成同步的配乐。
- 对话:使用引号来标记具体的台词。(例如:“这一定是钥匙,”他喃喃自语。)
- 音效 (SFX):明确描述声音。(示例:轮胎发出刺耳的尖叫声,引擎轰鸣。)
- 环境噪音:描述环境的音景。(示例:背景中回荡着微弱、诡异的嗡嗡声。)
这些视频展示了如何通过提供越来越详细的提示,让 Veo 3 生成音频。
| 提示 | 生成的输出 |
|---|---|
| 更多细节(对话和环境音) 太平洋西北地区雾气弥漫的森林远景。一男一女两位徒步旅行者疲惫不堪,正穿过蕨类植物丛,突然,男士停下脚步,盯着一棵树。特写:树皮上留有新鲜、深深的爪痕。男子:(手放在猎刀上)“那不是普通的熊。”Woman: (Voice tight with fear, scanning the woods) "Then what is it?" 粗糙的树皮、折断的树枝、潮湿泥土上的脚步声。一只孤鸟在鸣叫。 |
|
| 细节较少(对话) 剪纸动画。新图书管理员:“禁书放在哪里?”旧馆长:“我们没有。它们在守护我们。” |
|
不妨亲自尝试这些提示,听听音频效果! 试用 Veo
使用参考图片撰写提示
您可以使用一张或多张图片作为输入,利用 Veo 的图生视频功能来引导生成的视频。Veo 会将输入的图片用作初始帧。选择一张最接近您设想的视频第一场景的图片,为日常物品添加动画效果,让绘画作品更加生动,也可以为自然景观增添动感和声音。
| 提示 | 生成的输出 |
|---|---|
| 输入图片(由 Nano Banana 生成) 一张超写实的微距照片,显示在古朴的石制浴室水槽中,微型冲浪者正在海浪中冲浪。一个复古的黄铜水龙头正在流水,形成永不停歇的浪花。超现实、奇幻、明亮的自然光线。 |
|
| 输出视频(由 Veo 3.1 生成) 一个超现实的电影级微距视频。在石质洗手池中,小小的冲浪者在不断翻滚的波浪中冲浪。一个复古黄铜水龙头不断流出水,形成无尽的浪花。镜头在阳光普照的奇幻场景中缓慢平移,微缩人物在碧绿的水面上熟练地滑行。 |
|
借助 Veo 3.1,您可以使用参考图片或素材来指导生成的视频的内容。最多提供三张同一人物、角色或产品的素材资源图片。Veo 会在输出视频中保留主体的外观。
| 提示 | 生成的输出 |
|---|---|
| 参考图片(由 Nano Banana 生成) 一条深海安康鱼潜伏在幽暗的深海中,露出尖牙,诱饵发光。 |
|
| 参考图片(由 Nano Banana 生成) 一套粉色儿童公主服,配有魔杖和皇冠,背景为纯色产品背景。 |
|
| 输出视频(由 Veo 3.1 生成) 制作一个搞笑的卡通版视频,展示鱼儿穿着服装、游泳并挥舞魔杖的场景。 |
|
使用 Veo 3.1,您还可以通过指定视频的第一帧和最后一帧来生成视频。
| 提示 | 生成的输出 |
|---|---|
| 第一张图片(由 Nano Banana 生成) 一张高画质、逼真的正面图片,展示了一只姜黄色猫咪在法国里维埃拉海岸驾驶一辆红色敞篷赛车。 |
|
| 最后一张图片(由 Nano Banana 生成) 展示汽车从悬崖上起飞时的场景。 |
|
| 输出视频(由 Veo 3.1 生成) 可选 |
|
借助此功能,您可以定义起始帧和结束帧,从而精确控制镜头的构图。上传图片或使用之前生成的视频中的画面,确保场景的开始和结束完全符合您的设想。
撰写用于扩展的提示
如需使用 Veo 3.1(不适用于 Veo 3.1 Lite)延长 Veo 生成的视频,请将该视频作为输入,并可选择添加文本提示词。“延长”功能会锁定视频的最后一秒或最后 24 帧,并延续其中的动作。
请注意,如果视频的最后 1 秒内没有语音,则无法有效延长语音。
| 提示 | 生成的输出 |
|---|---|
| 输入视频(由 Veo 3.1 生成) 滑翔伞从山顶起飞,开始沿着山坡滑翔,俯瞰下方开满鲜花的山谷。 |
|
| 输出视频(由 Veo 3.1 生成) 延长此视频,让滑翔伞慢慢下降。 |
|
提示和输出示例
本部分提供了几个提示,重点介绍了描述性细节如何提升每个视频的效果。
冰柱
此视频演示了如何在提示中使用提示撰写基础知识中的元素。
| 提示 | 生成的输出 |
|---|---|
| 特写镜头(构图):冰冻的岩壁(背景)上融化的冰柱(主体),冷蓝色调(氛围),放大(相机运动),保持水滴(动作)的特写细节。 |
|
一位男士正在打电话
这些视频展示了如何通过提供越来越具体的细节来修改提示,从而让 Veo 根据您的喜好优化输出。
| 提示 | 生成的输出 |
|---|---|
| 细节较少 镜头推近,特写一位身着绿色风衣、神情绝望的男人。他正在绿色霓虹灯下用一部转盘式壁挂电话拨号。看起来就像电影场景。 |
|
| 更多细节 一个特写电影镜头,跟随一个身穿破旧绿色风衣的绝望男子,他在一个粗糙的砖墙上拨打转盘电话,沐浴在绿色霓虹灯招牌的诡异光芒中。镜头推近,展现出他紧绷的下颌和脸上刻画的绝望,他正挣扎着拨打电话。浅景深聚焦于他紧锁的眉头和黑色拨盘电话,将背景模糊成一片霓虹色彩和模糊的阴影,营造出一种紧迫感和孤立感。 |
|
雪豹
| 提示 | 生成的输出 |
|---|---|
| 简单提示: 一只长着雪豹般毛皮的可爱生物在冬日的森林中行走,3D 卡通风格渲染。 |
|
| 详细提示: Create a short 3D animated scene in a joyful cartoon style. 一个可爱的生物,有着雪豹般的毛皮、富有表现力的大眼睛和友好的圆形体态,在奇幻的冬季森林中快乐地欢跃。场景中应有圆润的积雪树木、轻轻飘落的雪花,以及透过树枝洒下的温暖阳光。这个生物欢快的动作和灿烂的笑容应该传达出纯粹的喜悦。采用欢快、温馨的基调,搭配明亮、愉悦的色彩和生动有趣的动画。 |
|
按写作要素分类的示例
以下示例展示了如何根据每个基本元素来优化提示。
主题和背景
指定主要焦点(主体)和背景或环境(背景)。
| 提示 | 生成的输出 |
|---|---|
| 一栋白色混凝土公寓楼的建筑渲染图,建筑采用流畅的有机形态,与郁郁葱葱的绿植和未来主义元素完美融合 |
|
| 一颗卫星在太空中漂浮,背景是月球和一些星星。 |
|
操作
指定主体正在做的事情(例如,走路、跑步或转头)。
| 提示 | 生成的输出 |
|---|---|
| 一个全景镜头,展现了一位女士在日落时分沿着海滩漫步,神情满足而放松地望向地平线。 |
|
样式
添加关键字,引导生成特定美学风格(例如超现实、复古、未来主义、黑色电影)。
| 提示 | 生成的输出 |
|---|---|
| 黑色电影风格,一男一女在街上行走,神秘,电影感,黑白。 |
|
镜头运动和构图
指定镜头的移动方式(主视角、航拍视图、无人机跟拍视图)和取景方式(全景、特写、低角度)。
| 提示 | 生成的输出 |
|---|---|
| 主视角镜头:一辆复古汽车在雨中行驶,加拿大夜晚,电影风格。 |
|
| 一只眼睛的特写,眼睛里倒映着城市。 |
|
氛围
配色方案和光线会影响氛围。尝试使用“柔和的橙色暖色调”“自然光”“日出”或“冷蓝色调”等字词。
| 提示 | 生成的输出 |
|---|---|
| 在阳光明媚的公园里,一个女孩抱着可爱的金毛猎犬小狗的特写镜头。 |
|
| 电影效果特写镜头,一位悲伤的女士在雨中乘坐巴士,冷蓝色调,悲伤氛围。 |
|
宽高比
Veo 允许您指定视频的宽高比。
| 提示 | 生成的输出 |
|---|---|
| 宽屏 (16:9) Create a video with a tracking drone view of a man driving a red convertible car in Palm Springs, 1970s, warm sunlight, long shadows. |
|
| 纵向 (9:16) 制作一个视频精彩集锦,突出展示夏威夷茂密雨林中壮丽瀑布的流畅流动。重点描绘逼真的水流、细致的树叶和自然的光线,以传达宁静的氛围。捕捉奔腾的水流、雾气缭绕的氛围,以及透过茂密树冠洒下的斑驳阳光。使用流畅、电影般的镜头移动来展示瀑布及其周围环境。力求营造一种宁静、写实的基调,让观看者仿佛置身于夏威夷雨林的宁静美景之中。 |
|
模型版本
如需了解 Veo 模型特有的更多使用详情,请参阅价格页面和速率限制。
Veo 3.1 预览版
| 属性 | 说明 |
|---|---|
| 模型代码 |
Gemini API
|
| 支持的数据类型 |
输入 文字广告、图片广告 输出 带音频的视频 |
| 限制 |
文本输入 1,024 个 token 输出视频 1 |
| 最后更新时间 | 2026 年 1 月 |
Veo 3.1 Fast 预览版
| 属性 | 说明 |
|---|---|
| 模型代码 |
Gemini API
|
| 支持的数据类型 |
输入 文字广告、图片广告 输出 带音频的视频 |
| 限制 |
文本输入 1,024 个 token 输出视频 1 |
| 最后更新时间 | 2026 年 1 月 |
Veo 3.1 Lite 预览版
| 属性 | 说明 |
|---|---|
| 模型代码 |
Gemini API
|
| 支持的数据类型 |
输入 文字、图片 输出 带音频的视频 |
| 限制 |
文本输入 1,024 个 token 输出视频 1 |
| 最后更新时间 | 2026 年 3 月 |
Veo 3(已弃用)
| 属性 | 说明 |
|---|---|
| 模型代码 |
Gemini API
|
| 支持的数据类型 |
输入 文字广告、图片广告 输出 带音频的视频 |
| 限制 |
文本输入 1,024 个 token 输出视频 1 |
| 最后更新时间 | 2025 年 7 月 |
Veo 3 Fast(已弃用)
| 属性 | 说明 |
|---|---|
| 模型代码 |
Gemini API
|
| 支持的数据类型 |
输入 文字广告、图片广告 输出 带音频的视频 |
| 限制 |
文本输入 1,024 个 token 输出视频 1 |
| 最后更新时间 | 2025 年 7 月 |
借助 Veo Fast 版本,开发者可以创作有声视频,同时保持高画质,并针对速度和商业用途进行优化。它们非常适合以编程方式生成广告的后端服务、用于快速 A/B 测试广告素材概念的工具,或需要快速生成社交媒体内容的应用。
后续步骤
- 通过在 Veo 快速入门 Colab 和 Veo 3.1 applet 中进行实验,开始使用 Veo 3.1 API。
- 通过我们的提示设计简介,了解如何撰写更出色的提示。