Los modelos de texto a video Wan generan videos a partir de entradas de texto, imágenes y audio. wan3.0-video admite hasta 30 segundos, relación de aspecto adaptativa, duración inteligente, resolución 480P/720P/1080P, alternancia de audio, audio de referencia, así como archivos y enlaces web de referencia.
Acceso rápido: Pruébelo en línea (Singapore | EE. UU. (Virginia) | China (Beijing)) | Referencia de API | Guía de prompts
Introducción
| Prompt de entrada | Video de salida (toma múltiple, con audio) |
Toma 1 La secuencia comienza con un plano general extremo. La cámara inicia en un ángulo bajo cerca del suelo y avanza por la pradera mientras se inclina hacia arriba. A medida que la cámara se eleva desde el nivel del suelo hasta una posición ligeramente elevada, el guepardo entra en el encuadre desde la izquierda. Esta toma establece una relación espacial clara al colocar al guepardo y al antílope que huye en la misma trayectoria. Toma 2 La cámara desciende a un nivel cercano al suelo y realiza un seguimiento hacia la derecha, paralelo al guepardo. El guepardo se mantiene consistentemente a la izquierda del centro, lo que crea un desplazamiento lateral continuo en el fondo. Durante un período, el movimiento de la cámara permanece estable para mejorar la sensación de velocidad y continuidad espacial. Toma 3 Mientras sigue moviéndose hacia la derecha, la cámara ejecuta un ligero arco a lo largo del interior de la trayectoria del guepardo. Este movimiento crea un sutil efecto orbital en el encuadre mientras la cámara continúa siguiendo al sujeto. Toma 4 La cámara ralentiza gradualmente su movimiento lateral y se vuelve relativamente estable mientras hace zoom simultáneamente. Esta acción estrecha el enfoque en la distancia decreciente entre el guepardo y el antílope. Toma 5 La cámara avanza nuevamente y ligeramente hacia abajo, pegándose al suelo para cerrar la distancia entre los dos animales. La toma se detiene en el punto crítico justo cuando las extremidades delanteras del guepardo están a punto de alcanzar los cuartos traseros del antílope, lo que crea una intensa presión y tensión. Esta acción está sincronizada con una partitura sinfónica en crescendo, un redoble de tambores que se densifica y los sonidos del viento y los pasos que impulsan el ritmo. En el momento final, el volumen de la música baja, dejando solo sonidos ambientales y rítmicos para crear una breve pausa. |
Antes de realizar una llamada a la API, obtenga una clave de API y configúrela como variable de entorno. Para usar un SDK, instale el SDK de DashScope. Todos los ejemplos utilizan llamadas asíncronas que envían una tarea de generación de video y sondean el resultado.
SDK de Python
ImportanteAsegúrese de que su DashScope SDK para Python sea versión 1.25.16 o posterior antes de ejecutar el siguiente código.
Si la versión es demasiado baja, pueden ocurrir errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# The API key varies by region. For more information about how to obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
print('please wait...')
rsp = VideoSynthesis.call(api_key=api_key,
model='wan3.0-video',
prompt='Shot 1: Opening with a long shot. The camera starts from a low angle close to the ground and moves forward across the grassland. At the same time, the camera moves upward, gradually raising the point of view from ground level to a slightly elevated position. A cheetah enters the frame from the left, on the same chase path as a fleeing antelope in front of it, establishing a clear foreground-background spatial relationship. Shot 2: The camera moves downward, returning to a position close to the ground, and pans right to follow the cheetah\'s movement, steadily tracking it from a parallel side view. The subject remains consistently positioned slightly to the left of the frame\'s center, creating a continuous lateral movement effect in the background. The camera movement stays stable for a while to enhance the sense of speed and spatial continuity. Shot 3: While maintaining the rightward movement, the camera moves in a slight arc along the inside of the cheetah\'s path. This creates a subtle circling effect in the shot, but the camera always moves in the same direction as the subject. Shot 4: Gradually slow down the lateral movement and transition to a relatively stable camera position. At the same time, execute a zoom-in, progressively narrowing the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward again and slightly downward, closing in on the space between the two animals near the ground. It holds the shot at the critical moment when the cheetah\'s forelimbs are about to reach the antelope\'s rear, creating intense pressure and tension. This is accompanied by a crescendoing symphonic score, an increasingly intense drumbeat, and the sounds of wind and footsteps to drive the rhythm. In the final moments, the music volume drops, leaving only ambient and rhythmic sounds for a brief pause.',
resolution="720P",
ratio="16:9",
duration=15,
watermark=True)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("video_url:", rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
SDK de Java
ImportanteAsegúrese de que su DashScope SDK para Java sea versión 2.22.14 o posterior antes de ejecutar el siguiente código.
Si la versión es demasiado baja, pueden ocurrir errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// API keys vary by region. To obtain an API key, visit: https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan3.0-video")
.prompt("Shot 1: Open with a long shot. The camera starts at a low angle near the ground, dollying forward across the grassland while simultaneously craning up. The perspective lifts from ground level to a slightly elevated position, allowing a cheetah to enter the frame from the left, on the same chase path as a fleeing antelope ahead, establishing a clear spatial depth. Shot 2: The camera moves down to near ground level and tracks right, following the cheetah's movement. It maintains a stable, parallel tracking shot. The subject remains just left of the frame's center, creating a continuous lateral movement in the background. The camera motion stays steady for a period to enhance the sense of speed and spatial continuity. Shot 3: While maintaining the rightward track, the camera executes a slight arc along the inner side of the cheetah's path. This creates a subtle orbiting effect in the shot, while the camera continues to point in the same direction as the subject. Shot 4: Gradually slow the lateral movement, transitioning to a relatively stable camera position. Simultaneously, execute a zoom-in, progressively narrowing the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward and slightly downward again, staying close to the ground to close in on the space between the two. It stops at the critical moment just as the cheetah's forelimbs are about to reach the antelope's rear, creating intense pressure and tension. This is accompanied by a gradually intensifying orchestral score, increasingly dense drumbeats, and the sounds of wind and footsteps to drive the rhythm. In the final stage, the music volume is lowered, leaving only ambient and rhythmic sounds for a brief pause.")
.duration(15)
.resolution("720P")
.ratio("16:9")
.watermark(true)
.build();
System.out.println("please wait...");
VideoSynthesisResult result = vs.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan3.0-video",
"input": {
"prompt": "Shot 1: An extreme long shot opens the scene. The camera starts from a low angle near the ground and moves forward across the grassland. It simultaneously tilts up, raising the perspective from ground level to a slightly higher position. This brings a cheetah into the frame from the left, placing it on the same chase path as a fleeing antelope ahead and establishing a clear spatial relationship. Shot 2: The camera moves down, returning to near ground level, and tracks right along the cheetahs path of motion. It maintains a stable, parallel side-on follow shot, keeping the subject in the left-center of the frame as the background scrolls horizontally. The camera movement remains steady for a period to enhance the sense of speed and spatial continuity. Shot 3: While continuing to track right, the camera makes a slight arc along the inner side of the cheetahs path, creating a subtle orbiting effect while always moving in the same direction as the subject. Shot 4: The camera gradually slows its horizontal movement and transitions to a relatively stable position while zooming in. This progressively compresses the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward again and slightly down, closing in on the space between them near the ground. It stops at the critical moment when the cheetahs forelimbs are about to reach the antelopes rear, creating intense pressure and tension. This is accompanied by a crescendo of symphonic music, an accelerating drumbeat, and the sounds of wind and paws hitting the ground to drive the rhythm. In the final stage, the music fades, leaving only ambient sounds and the rhythmic beat for a brief pause."
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"watermark": true,
"duration": 15
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de ejemplo: Modelos wan2.6 y anteriores
SDK de Python
ImportanteAsegúrese de que su DashScope SDK para Python sea versión 1.25.16 o posterior antes de ejecutar el siguiente código.
Si la versión es demasiado baja, pueden ocurrir errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
api_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")
print('please wait...')
rsp = VideoSynthesis.call(api_key=api_key,
model='wan2.6-t2v',
prompt='A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization.',
size="1280*720",
duration=15,
shot_type="multi",
watermark=True)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("video_url:", rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
SDK de Java
ImportanteAsegúrese de que su DashScope SDK para Java sea versión 2.22.14 o posterior antes de ejecutar el siguiente código.
Si la versión es demasiado baja, pueden ocurrir errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key.
// The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2v")
.prompt("A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization.")
.duration(15)
.size("1280*720")
.shotType("multi")
.watermark(true)
.build();
System.out.println("please wait...");
VideoSynthesisResult result = vs.call(param);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan2.6-t2v",
"input": {
"prompt": "A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization."
},
"parameters": {
"size": "1280*720",
"watermark": true,
"duration": 15,
"shot_type":"multi"
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
video_urles válido durante 24 horas. Descargue el video oportunamente.
{
"request_id": "c1209113-8437-424f-a386-xxxxxx",
"output": {
"task_id": "966cebcd-dedc-4962-af88-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-result-sh.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx"
}
}
Disponibilidad
Los modelos compatibles varían según la región. Los recursos están aislados entre regiones. Al realizar una llamada, asegúrese de que su modelo, URL de endpoint y clave de API pertenezcan todos a la misma región. Las llamadas entre regiones fallarán.
Modelos compatibles:
Global
Si selecciona el ámbito de implementación Global, los recursos de cómputo para inferencia del modelo se programan dinámicamente a nivel mundial. Los datos estáticos se almacenan en la región seleccionada. Regiones compatibles: EE. UU. (Virginia), Germany (Frankfurt), China (Hong Kong).
Modelo | Características | Modalidad de entrada | Especificaciones del video de salida |
wan2.6-t2v | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: 5s, 10s, 15s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
International
Si selecciona el ámbito de implementación International, los recursos de cómputo para inferencia del modelo se programan dinámicamente a nivel mundial, excluyendo China continental. Los datos estáticos se almacenan en la región seleccionada. Región compatible: Singapore.
| Modelo | Características | Modalidad de entrada | Especificaciones del video de salida |
wan2.7-t2v-2026-04-25 | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.7-t2v | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.6-t2v | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.5-t2v-preview | Video con audio Sincronización de audio y video | Texto, audio | Opciones de resolución: 480P, 720P, 1080P Duración del video: 5s, 10s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.2-t2v-plus | Video silencioso
| Text | Opciones de resolución: 480P, 1080P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.1-t2v-turbo | Video silencioso | Text | Opciones de resolución: 480P, 720P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.1-t2v-plus | Video silencioso | Text | Opciones de resolución: 720P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
China continental
Si selecciona el ámbito de implementación de China continental, los recursos de cómputo para inferencia del modelo están restringidos a China continental. Los datos estáticos se almacenan en la región seleccionada. Región compatible: China (Beijing).
| Modelo | Características | Modalidad de entrada | Especificaciones del video de salida |
wan2.7-t2v-2026-04-25 | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.7-t2v | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.6-t2v | Video con audio Narrativa de toma múltiple, sincronización de audio y video | Texto, audio | Opciones de resolución: 720P, 1080P Duración del video: [2s, 15s] (entero) Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.5-t2v-preview | Video con audio Sincronización de audio y video | Texto, audio | Opciones de resolución: 480P, 720P, 1080P Duración del video: 5s, 10s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wan2.2-t2v-plus | Video silencioso
| Text | Opciones de resolución: 480P, 1080P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wanx2.1-t2v-turbo | Video silencioso | Text | Opciones de resolución: 480P, 720P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
wanx2.1-t2v-plus | Video silencioso | Text | Opciones de resolución: 720P Duración del video: 5s Especificaciones definidas: 30 fps, MP4 (codificación H.264) |
NotaEl código de ejemplo en este tema se aplica a la región de Singapore.
Capacidades principales
Crear videos de toma múltiple
Modelos compatibles: wan3.0, wan2.7, and wan2.6 series.
Descripción: Cambia automáticamente entre tomas (por ejemplo, de un plano general a un primer plano). Ideal para videos musicales y narrativas cinematográficas.
Parámetros:
- wan2.7: El parámetro
shot_typeno es obligatorio. Describa la estructura de tomas en elpromptutilizando lenguaje natural, como marcas de tiempo para definir las tomas. Si elpromptno contiene descripciones de la estructura de tomas, el modelo analiza la semántica y determina automáticamente si debe generar un video de una sola toma o de múltiples tomas. - wan2.6: El parámetro
shot_typedebe establecerse en"multi", y el parámetroprompt_extenddebe establecerse entruepara habilitar la reescritura inteligente y optimizar las descripciones de las tomas.
| Prompt de entrada | Video de salida (wan3.0) |
Una visión de armonía entre la tecnología futura y la naturaleza. Toma 1 [0-2s]: Plano general de un jardín aéreo en una ciudad futurista, con plantas flotantes meciéndose suavemente con la brisa. Toma 2 [2-4s]: Un robot jardinero poda cuidadosamente las plantas con movimientos precisos y elegantes. Toma 3 [4-7s]: La luz del sol atraviesa una cúpula transparente, iluminando todo el jardín y mostrando la fusión perfecta de tecnología y naturaleza. Toma 4 [7-10s]: La cámara se aleja para revelar la gran escala de toda la ciudad futurista, con el jardín aéreo como solo una parte de ella. | |
Este es un clip de película de artes marciales centrado en un duelo intenso. En un claro de piedra bajo el sol del mediodía, dos hombres se abalanzan el uno sobre el otro. Uno golpea con la palma, pero su oponente gira y bloquea con el brazo, y el impacto levanta polvo del suelo. Luego intercambian golpes rápidos y palmadas en un espacio reducido. Uno salta en el aire para ejecutar una serie de patadas fuertes, obligando a su oponente a cruzar los brazos para bloquear y deslizarse varios metros hacia atrás, dejando marcas blancas claras en la superficie de piedra. Finalmente, se separan, respirando pesadamente y cruzando miradas. La escena presenta una textura de acción realista con iluminación nítida, creando un tono que cambia de una explosión poderosa a un tenso enfrentamiento. |
SDK de Python
Asegúrese de que su DashScope SDK para Python sea versión
1.25.16o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.
# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
api_key = os.getenv("DASHSCOPE_API_KEY")
def sample_async_call_t2v():
# Asynchronous invocation that returns a task_id.
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan3.0-video',
prompt='A vision of harmony between future technology and nature. Shot 1 [0-2s]: Wide shot of an aerial garden in a futuristic city, floating plants swaying gently in the breeze. Shot 2 [2-4s]: A robot gardener carefully trims plants with precise, graceful movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the grand scale of the entire futuristic city, with the aerial garden as just one part of it.',
resolution='720P',
ratio='16:9',
duration=10,
watermark=True,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
# Wait for the asynchronous task to complete.
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_t2v()
SDK de Java
Asegúrese de que su DashScope SDK para Java sea versión
2.22.14o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key.
// The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan3.0-video")
.prompt("A vision of harmony between future technology and nature. Shot 1 [0-2s]: Wide shot of an aerial garden in a futuristic city, floating plants swaying gently in the breeze. Shot 2 [2-4s]: A robot gardener carefully trims plants with precise, graceful movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the grand scale of the entire futuristic city, with the aerial garden as just one part of it.")
.resolution("720P")
.ratio("16:9")
.duration(10)
.watermark(true)
.seed(12345)
.build();
// Asynchronous invocation
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan3.0-video",
"input": {
"prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \".",
"audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3"
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"duration": 10
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de ejemplo: wan2.6
SDK de Python
Asegúrese de que su DashScope SDK para Python sea versión
1.25.16o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def sample_async_call_t2v():
# Make an asynchronous invocation to return a task_id.
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan2.6-t2v',
prompt='Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part.',
size='1280*720',
duration=10,
shot_type='multi',
watermark=True,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
# Wait for the asynchronous task to complete.
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_t2v()
SDK de Java
Asegúrese de que su versión de DashScope Java SDK sea
2.22.14o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2v")
.prompt("Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part.")
.negativePrompt("")
.size("1280*720")
.duration(10)
.shotType("multi")
.watermark(true)
.seed(12345)
.build();
// Asynchronous invocation
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan2.6-t2v",
"input": {
"prompt": "Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part."
},
"parameters": {
"size": "1280*720",
"watermark": true,
"duration": 10,
"shot_type": "multi"
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Sincronizar audio y video
Modelos compatibles: wan3.0, wan2.7, wan2.6, and wan2.5 series.
Descripción: Los personajes del video pueden "hablar" o cantar, con movimientos de la boca sincronizados con el audio. Para más ejemplos, consulte Generación de audio para video.
Parámetros:
- Proporcionar un archivo de audio: Establezca
audio_url. El modelo sincroniza los movimientos labiales con el archivo de audio. - Doblaje automático: Sin un
audio_url, el modelo genera automáticamente video con audio de forma predeterminada, añadiendo efectos de sonido de fondo, música o voces basándose en el contenido visual.
| Ejemplo de entrada | Video de salida (video con audio habilitado) |
Prompt de entrada: Toma desde un ángulo bajo, en primer plano medio, con tonos cálidos, iluminación mixta (la luz práctica de la lámpara de escritorio se mezcla con la luz nublada de la ventana), iluminación lateral y composición central. En una oficina clásica de detective, estanterías de madera están llenas de archivos de casos antiguos y ceniceros. Una lámpara de escritorio verde ilumina un expediente abierto en el centro del escritorio. Un zorro, vestido con una gabardina marrón oscuro y un sombrero fedora gris claro, está sentado en una silla de cuero; su pelaje es carmesí, su cola descansa ligeramente sobre el borde y sus dedos pasan lentamente páginas amarillentas. Afuera, cae una llovizna constante bajo un cielo azul, rayando el cristal con trazos sinuosos. Levanta lentamente la cabeza, sus orejas se mueven ligeramente, sus ojos ámbar miran directamente a la cámara y su boca se mueve claramente mientras habla con una voz suave y cínica: 'El caso estaba frío, más frío que un pez en invierno. Pero cada pollo tiene sus secretos, y yo, por mi parte, tenía la intención de encontrarlos'. Audio de entrada: |
SDK de Python
Asegúrese de que su DashScope SDK para Python sea versión
1.25.16o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.
# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
api_key = os.getenv("DASHSCOPE_API_KEY")
def sample_async_call_t2v():
# Asynchronous invocation that returns a task_id.
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan3.0-video',
prompt="Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them '.",
audio_url='https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3',
resolution='720P',
ratio='16:9',
duration=10,
watermark=True,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
# Wait for the asynchronous task to complete.
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_t2v()
SDK de Java
Asegúrese de que su DashScope SDK para Java sea versión
2.22.14o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key.
// The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan3.0-video")
.prompt("Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them '.")
.audioUrl("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3")
.resolution("720P")
.ratio("16:9")
.duration(10)
.watermark(true)
.seed(12345)
.build();
// Asynchronous invocation
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan3.0-video",
"input": {
"prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \". ",
"audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3"
},
"parameters": {
"resolution": "720P",
"ratio": "16:9",
"watermark": true,
"duration": 10
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de ejemplo: wan2.6
SDK de Python
Asegúrese de que su DashScope SDK para Python sea versión
1.25.16o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"
# API keys vary by region. To get an API key, visit: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def sample_async_call_t2v():
# Make an asynchronous invocation to return a task_id.
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan2.6-t2v',
prompt="Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them '.",
audio_url='https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3',
size='1280*720',
duration=10,
watermark=True,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
# Wait for the asynchronous task to complete.
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_t2v()
SDK de Java
Asegúrese de que su DashScope SDK para Java sea versión
2.22.14o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx"
// API keys vary by region. To get an API key, visit: https://www.alibabacloud.com/help/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2v")
.prompt("Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them '.")
.audioUrl("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3")
.negativePrompt("")
.size("1280*720")
.duration(10)
.watermark(true)
.seed(12345)
.build();
// Make an asynchronous invocation.
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result.
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan2.6-t2v",
"input": {
"prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \".",
"audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3"
},
"parameters": {
"size": "1280*720",
"duration": 10
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Generar videos silenciosos
Modelos compatibles: wan2.2 series, wan2.1 series.
Descripción: Ideal para escenarios que requieren solo contenido visual, como pósteres dinámicos y videos cortos silenciosos.
Parámetros: Los modelos wan2.2 y anteriores generan videos silenciosos de forma predeterminada. No se necesita configuración adicional.
| Prompt de entrada | Video de salida (video silencioso) |
Luz de contorno, bajo contraste, primer plano medio, luz diurna, composición cargada a la izquierda, toma limpia de una sola persona, tonos cálidos, luz suave, luz de día soleado, luz lateral, día. Una joven está sentada en un campo de hierba alta con dos burros peludos detrás de ella. La niña, de unos once o doce años, lleva un sencillo vestido floral, tiene el cabello en dos trenzas y muestra una sonrisa inocente. Está sentada con las piernas cruzadas, tocando suavemente las flores silvestres a su lado. Los burros son robustos, tienen las orejas erguidas y miran con curiosidad hacia la cámara. La luz del sol baña el campo, creando una escena cálida y natural. |
SDK de Python
Asegúrese de que su DashScope SDK para Python sea versión
1.25.16o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import os
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.
# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
api_key = os.getenv("DASHSCOPE_API_KEY")
def sample_async_call_t2v():
# Asynchronous invocation that returns a task_id.
rsp = VideoSynthesis.async_call(api_key=api_key,
model='wan2.2-t2v-plus',
prompt='Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene.',
size='832*480',
watermark=True,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print("task_id: %s" % rsp.output.task_id)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
# Wait for the asynchronous task to complete.
rsp = VideoSynthesis.wait(task=rsp, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_async_call_t2v()
SDK de Java
Asegúrese de que su DashScope SDK para Java sea versión
2.22.14o posterior. Para actualizar el SDK, consulte Instalar el SDK .
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisParam;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Text2Video {
static {
// The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/model-studio/text-to-video-api-reference
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key.
// The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/model-studio/get-api-key.
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.2-t2v-plus")
.prompt("Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene.")
.size("832*480")
.watermark(true)
.seed(12345)
.build();
// Asynchronous invocation
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("please wait...");
// Get the result
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
text2video();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
curl
Paso 1: Crear una tarea para obtener el ID de tareacurl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
-H 'X-DashScope-Async: enable' \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "wan2.2-t2v-plus",
"input": {
"prompt": "Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene."
},
"parameters": {
"size": "832*480",
"watermark": true
}
}'
Paso 2: Recuperar el resultado mediante el ID de tareaReemplace {task_id} con el valor task_id devuelto por la llamada a la API anterior. El task_id es válido para consultas durante 24 horas. Reemplace {WorkspaceId} con su ID de espacio de trabajo real.
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Audio de entrada
-
Número de archivos: Uno.
-
Métodos de entrada:
- URL pública: HTTP o HTTPS.
Video de salida
-
Número de videos: Uno.
-
Formato: MP4. Para más información, consulte Especificaciones de video.
-
Caducidad de URL: 24 horas.
-
Dimensiones del video:
- Los modelos wan3.0 y wan2.7 utilizan los parámetros
resolutionyratio. - Los modelos wan2.6 y anteriores utilizan el parámetro
size.
- Los modelos wan3.0 y wan2.7 utilizan los parámetros
Facturación y limitación de tasa
-
Para obtener detalles sobre la cuota gratuita y los precios, consulte Wanx-Text-to-Video.
-
Para la limitación de tasa del modelo, consulte la serie Wanxiang.
-
Detalles de facturación:
- La entrada es gratuita. La salida se factura por cada segundo de video generado correctamente.
- Las llamadas fallidas al modelo o los errores de procesamiento no generan cargos ni consumen cuota gratuita.
- Texto a video también admite planes de ahorro.
Referencia de API
Referencia de API de texto a video
FAQ
P: ¿Qué cambios de código se necesitan para actualizar de wan2.7 a wan3.0?
- Nombre del modelo: Cambie
modeldewan2.7-t2v-*awan3.0-video. - Duración extendida: wan3.0 admite hasta 30 segundos (wan2.7 admite hasta 15 segundos). Establezca
durationen un número entero entre 2 y 30. - Nueva entrada de archivo y web: wan3.0 admite pasar
type: "file"(docx, ppt, pdf, etc.) otype: "link"(URL web pública) eninput.media. El modelo comprende automáticamente el contenido y genera un video. Estos dos tipos no se pueden utilizar simultáneamente.
P: Los videos generados en la consola tienen una marca de agua. ¿Cómo la elimino?
- La página de generación de video en la consola de Model Studio no proporciona un interruptor de marca de agua, por lo que no puede desactivar la marca de agua en la consola.
- Cuando llame al modelo a través de la API,
watermarkesfalsede forma predeterminada: si lo omite o lo establece enfalse, no se añade ninguna marca de agua. El código de ejemplo en este tema pasawatermark=true; cámbielo afalsepara eliminar la marca de agua.
P: Compré un plan de ahorro de propósito general de IA. ¿Por qué los videos generados todavía tienen una marca de agua?
- Un plan de ahorro de propósito general de IA solo compensa su costo. No cambia la salida del modelo y no tiene relación con si un video lleva marca de agua.
- La marca de agua se controla únicamente mediante el parámetro
watermarkde la API y solo se añade cuando se pasatruede forma explícita.