Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Referencia de la API de texto a video de Wan2.7

Última actualización: Oct 12, 2026

El modelo de texto a video Wan genera videos fluidos a partir de prompts de texto.

Referencias: Guía del usuario

Disponibilidad

Coincida la región de su modelo, URL de endpoint y clave de API. Las llamadas entre regiones fallarán.

NotaEl código de ejemplo en este tema utiliza la región de Singapur.

ImportanteAlibaba Cloud Model Studio ha lanzado dominios específicos de espacio de trabajo para las regiones de China (Beijing) y Singapur. Los nuevos dominios dedicados ofrecen un rendimiento superior y una mayor estabilidad para las solicitudes de inferencia. Recomendamos migrar a los nuevos dominios:

  • China (Pekín): de https://dashscope.aliyuncs.com a https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapur: de https://dashscope-intl.aliyuncs.com a https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

{WorkspaceId} es su ID de espacio de trabajo, que se encuentra en la página Workspace Details de la consola de Alibaba Cloud Model Studio. El dominio existente permanece totalmente funcional.

HTTP (wan2.7)

ImportanteEsta interfaz utiliza el nuevo protocolo y admite únicamente wan2.7.

Las tareas de texto a video tardan entre 1 y 5 minutos. La API utiliza invocación asíncrona: Crear una tarea → Sondear el resultado.

Paso 1: Crear una tarea

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Nota

  • Después de crear la tarea, utilice el task_id devuelto para consultar el resultado. El task_id es válido durante 24 horas. No cree tareas duplicadas. En su lugar, utilice el sondeo para recuperar el resultado.
  • Para obtener orientación para principiantes, consulte Llamar a APIs con Postman o cURL.

Parámetros de solicitud

Narrativa de múltiples tomas

Controle la estructura de tomas con lenguaje natural en el prompt. El parámetro shot_type no tiene efecto.

  • Toma única: Introduzca "Generate a single-shot video".
  • Toma múltiple: Introduzca "Generar un video de toma múltiple" o describa las tomas con marcas de tiempo (por ejemplo, "Toma 1 [0–3 segundos] plano general: Calle lluviosa de Nueva York por la noche").
  • Predeterminado: Si no se especifica, el modelo interpreta el contenido de prompt.
curl --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.7-t2v-2026-06-12",
        "input": {
            "prompt": "A tense detective story with cinematic storytelling. Shot 1 [0–3 seconds] wide shot: Rainy New York street at night, neon lights flicker, a detective in a black trench coat walks briskly. Shot 2 [3–6 seconds] medium shot: The detective enters an old building, rain wets his coat, the door closes slowly behind him. Shot 3 [6–9 seconds] close-up: The detective's focused eyes, distant sirens sound, he frowns slightly. Shot 4 [9–12 seconds] medium shot: The detective moves carefully down a dim hallway, his flashlight illuminating the way. Shot 5 [12–15 seconds] close-up: The detective discovers a key clue, his face shows sudden realization."
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9",
            "prompt_extend": true,
            "watermark": true,
            "duration": 15
        }
    }'

Proporcionar un archivo de audio

Especifique una URL de archivo de audio personalizada en el parámetro input.audio_url.

curl --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.7-t2v-2026-06-12",
        "input": {
            "prompt": "An epic and cute scene. A small, adorable cartoon kitten general, wearing exquisitely detailed golden armor and a slightly oversized helmet, stands bravely on a cliff. He rides a small but heroic warhorse and says: 'The long clouds of Qinghai darken the snowy mountains, a lone city gazes at Yumen Pass from afar. Through a hundred battles in the yellow sand, the golden armor is worn, but we will not return until we have broken Loulan'. Below the cliff, a vast and endless army of mice with makeshift weapons is charging forward. This is a dramatic, large-scale battle scene inspired by ancient Chinese war epics. In the distance, dark clouds gather in the sky over the snowy mountains. The overall atmosphere is a comical and epic fusion of 'cute' and 'domineering'.",
            "audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250923/hbiayh/%E4%BB%8E%E5%86%9B%E8%A1%8C.mp3"
        },
        "parameters": {
            "resolution": "1080P",
            "ratio": "16:9",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Doblaje automático

Sin input.audio_url, el modelo genera música de fondo o efectos de sonido que coinciden con el contenido del video.

curl --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.7-t2v-2026-06-12",
        "input": {
            "prompt": "An epic and cute scene. A small, adorable cartoon kitten general, wearing exquisitely detailed golden armor and a slightly oversized helmet, stands bravely on a cliff. He rides a small but heroic warhorse and says: 'The long clouds of Qinghai darken the snowy mountains, a lone city gazes at Yumen Pass from afar. Through a hundred battles in the yellow sand, the golden armor is worn, but we will not return until we have broken Loulan'. Below the cliff, a vast and endless army of mice with makeshift weapons is charging forward. This is a dramatic, large-scale battle scene inspired by ancient Chinese war epics. In the distance, dark clouds gather in the sky over the snowy mountains. The overall atmosphere is a comical and epic fusion of 'cute' and 'domineering'."
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Usar un prompt negativo

Utilice negative_prompt para excluir el elemento "flower" y evitar que aparezca en el video.

curl --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.7-t2v-2026-06-12",
        "input": {
            "prompt": "A kitten running in the moonlight",
            "negative_prompt": "flower"
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9"
        }
    }'

CLI de dashscope

Llamada a través de la línea de comandos dashscope.

export DASHSCOPE_API_KEY="your-api-key"
# Replace {WorkspaceId} with your workspace ID, ap-southeast-1 with your region (e.g., us-east-1, eu-central-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
dashscope video-synthesis create -m wan2.7-t2v -p "a kitten running"

ImportanteEl asistente interactivo SDK Expert puede realizar las mismas tareas de desarrollo y solución de problemas mediante lenguaje natural; consulte

DashScope SDK Expert.

Para la tabla completa de regiones, consulte Resumen de URL base.

Encabezados

Content-Type string (Requerido)

El tipo de contenido de la solicitud. Debe ser application/json.

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

X-DashScope-Async string (Requerido)

Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser enable.

ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls".

Cuerpo de la solicitud

model string (Obligatorio)

Nombre del modelo. Para modelos y precios, consulte Precios de modelos.

Ejemplo: wan2.7-t2v, wan2.7-t2v-2026-06-12.

input object (Obligatorio)

Datos de entrada, incluido el prompt.

Propiedades

prompt string (Obligatorio)

Prompt de texto que describe el contenido del video y el estilo visual.

Admite chino e inglés. Cada carácter o letra cuenta como uno. El texto que exceda el límite se trunca automáticamente. Longitud máxima según el modelo:

  • wan2.7-t2v, wan2.7-t2v-2026-06-12: Hasta 5,000 caracteres.

Ejemplo: Un gatito corriendo bajo la luz de la luna.

Para obtener consejos, consulte la Guía de prompts de texto a video/imagen a video.

negative_prompt string (Opcional)

Elementos a excluir del video generado.

Admite chino e inglés. Máximo de 500 caracteres; el texto más largo se trunca automáticamente.

Ejemplo: baja resolución, error, peor calidad, baja calidad, deformado, dedos adicionales, malas proporciones.

audio_url string (Opcional)

URL del archivo de audio para la generación de video.

Formatos admitidos:

  1. URL pública:

Límites de audio:

  • Formato: WAV, MP3.
  • Duración: 2–30 segundos.
  • Tamaño de archivo: Hasta 15 MB.
  • Manejo de duración: Si el audio excede el valor de duration (por ejemplo, 5 segundos), solo se utilizan los primeros 5 segundos. Si el audio es más corto que el video, el resto del video permanece en silencio. Por ejemplo, audio de 3 segundos con un video de 5 segundos produce 3 segundos de audio seguidos de 2 segundos de silencio.

parameters object (Opcional)

Parámetros de generación de video: resolución, reescritura de prompts y marca de agua.

Propiedades

resolution string (Opcional)

ImportanteLa resolución afecta el costo. Consulte Precios de modelos antes de realizar la llamada.

Nivel de resolución del video generado. Controla la claridad de salida (recuento total de píxeles).

  • wan2.7-t2v, wan2.7-t2v-2026-06-12: Valores válidos: 720P, 1080P. Predeterminado: 1080P.

ratio string (Opcional)

Relación de aspecto del video de salida.

  • 16:9 (predeterminado)
  • 9:16
  • 1:1
  • 4:3
  • 3:4

Resoluciones de salida (ancho*alto) por relación de aspecto:

Nivel de resolución

Relación de aspecto

Resolución del video de salida (ancho*alto)

720P

16:9

1280*720

9:16

720*1280

1:1

960*960

4:3

1104*832

3:4

832*1104

1080P

16:9

1920*1080

9:16

1080*1920

1:1

1440*1440

4:3

1648*1248

3:4

1248*1648

duration integer (Opcional)

ImportanteLa duración afecta el costo. La facturación es por segundo. Consulte Precios de modelos antes de realizar la llamada.

Duración del video de salida, en segundos.

  • wan2.7-t2v, wan2.7-t2v-2026-06-12: Un número entero de 2 a 15. Predeterminado: 5.

prompt_extendboolean (Opcional)

Habilita la reescritura de prompts. Cuando está habilitado, un LLM reescribe el prompt de entrada para mejorar la calidad de generación. Es ideal para prompts cortos, pero añade latencia.

  • true (predeterminado)
  • false

watermark boolean (Opcional)

Añade una marca de agua en la esquina inferior derecha con el texto "AI Generated".

  • false (predeterminado)
  • true

seed integer (Opcional)

La semilla de número aleatorio debe ser un entero en el rango [0, 2147483647].

Si no se especifica, se genera una semilla aleatoria. Una semilla fija mejora la reproducibilidad.

Dado que la generación del modelo es probabilística, la misma semilla no garantiza resultados idénticos.

Parámetros de respuesta

Respuesta exitosa

Guarde el task_id para consultar el estado y el resultado de la tarea.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Respuesta de error

Error en la creación de la tarea. Consulte Códigos de error.

{
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

Salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

Paso 2: Consultar el resultado

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Nota

  • Recomendación de sondeo: La generación de video tarda varios minutos. Utilice un mecanismo de sondeo con un intervalo razonable, como 15 segundos.
  • Transición de estado de la tarea: PENDING → RUNNING → SUCCEEDED o FAILED.
  • Enlace de resultado: Después de que una tarea tenga éxito, se devuelve una URL de video válida durante 24 horas. Descargue y guarde el video en un almacenamiento permanente, como OSS.
  • task_idvalidez: 24 horas. Después de este período, las consultas devuelven el estado de la tarea como UNKNOWN.

Parámetros de solicitud

Consultar resultado de la tarea

Reemplace {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"
Encabezados

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

Parámetros de ruta

task_id string (Obligatorio)

El ID de la tarea.

Parámetros de respuesta

Tarea ejecutada correctamente

Las URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato.

{
    "request_id": "caa62a12-8841-41a6-8af2-xxxxxx",
    "output": {
        "task_id": "eff1443c-ccab-4676-aad3-xxxxxx",
        "task_status": "SUCCEEDED",
        "submit_time": "2025-09-29 14:18:52.331",
        "scheduled_time": "2025-09-29 14:18:59.290",
        "end_time": "2025-09-29 14:23:39.407",
        "orig_prompt": "An epic and cute scene. A small, adorable cartoon kitten general, wearing exquisitely detailed golden armor and a slightly oversized helmet, stands bravely on a cliff. He rides a small but heroic warhorse and says: 'The long clouds of Qinghai darken the snowy mountains, a lone city gazes at Yumen Pass from afar. Through a hundred battles in the yellow sand, the golden armor is worn, but we will not return until we have broken Loulan'. Below the cliff, a vast and endless army of mice with makeshift weapons is charging forward. This is a dramatic, large-scale battle scene inspired by ancient Chinese war epics. In the distance, dark clouds gather in the sky over the snowy mountains. The overall atmosphere is a comical and epic fusion of 'cute' and 'domineering'.",
        "video_url": "https://dashscope-result-sh.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx"
    },
    "usage": {
        "duration": 10,
        "input_video_duration": 0,
        "output_video_duration": 10,
        "video_count": 1,
        "ratio": "16:9",
        "SR": 720
    }
}

Error en la ejecución de la tarea

Cuando una tarea falla, task_status es FAILED con un código de error y un mensaje. Consulte Códigos de error.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size does not match xxxxxx"
    }
}

Consulta de tarea caducada

El task_id es válido durante 24 horas. Después de este período, las consultas devuelven el siguiente error.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

outputobject

Salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.
Transiciones de estado durante el sondeo:
  • PENDING → RUNNING → SUCCEEDED o FAILED.
  • El estado inicial de la consulta suele ser PENDING o RUNNING.
  • Cuando el estado cambia a SUCCEEDED, la respuesta contiene la URL del video generado.
  • Si el estado es FAILED, revise el mensaje de error y reintente la tarea.

submit_time string

La hora en que se envió la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

La hora en que se ejecutó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

end_time string

La hora en que se completó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

video_url string

URL del video generado. Se devuelve solo cuando task_status es SUCCEEDED.

Válido durante 24 horas. El video está en formato MP4 con codificación H.264.

orig_prompt string

El prompt de entrada original, correspondiente al parámetro de solicitud prompt.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

usage object

Estadísticas de salida. Se devuelven solo para tareas exitosas.

Propiedades

duration float

Duración total del video, utilizada para facturación.

Igual a output_video_duration.

input_video_duration integer

Valor fijo: 0.

output_video_duration integer

Duración del video de salida en segundos. Coincide con el valor de input.duration.

SR integer

Nivel de resolución del video de salida. Ejemplo: 720.

ratio string

Relación de aspecto del video de salida. Ejemplo: 16:9.

video_count integer

Número de videos generados. Siempre 1.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

HTTP (wan2.6 y anteriores)

ImportanteEsta interfaz utiliza el protocolo heredado y admite wan2.6 y anteriores (wan2.5/wan2.2/wan2.1).

Las tareas de texto a video tardan entre 1 y 5 minutos, por lo que la API utiliza invocación asíncrona: Crear una tarea → Sondear el resultado.

Paso 1: Crear una tarea

Singapore

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Virginia

POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Beijing

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis

Fráncfort

POST https:// {WorkspaceId}.eu-central-1.maas.aliyuncs.com/ api/v1/services/aigc/video-generation/video-synthesis

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Nota

  • Después de crear la tarea, utilice el task_id devuelto para consultar el resultado. El task_id es válido durante 24 horas. No cree tareas duplicadas. En su lugar, utilice el sondeo para recuperar el resultado.
  • Para obtener orientación para principiantes, consulte Llamar a APIs con Postman o cURL.

Parámetros de solicitud

Narrativa de múltiples tomas

  • Para crear una narrativa de múltiples tomas, establezca shot_type en "multi".
  • Establezca prompt_extend en true para habilitar la reescritura de prompts para la optimización del guion gráfico.
curl --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",
            "prompt_extend": true,
            "duration": 10,
            "shot_type":"multi"
        }
    }'

Pasar un archivo de audio

Modelos compatibles: series wan2.6 y wan2.5.

Establezca el parámetro input.audio_url en una URL de archivo de audio personalizada.

curl --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.5-t2v-preview",
        "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": "832*480",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Doblaje automático

Modelos compatibles: series wan2.6 y wan2.5.

Sin el parámetro input.audio_url, el modelo genera música de fondo o efectos de sonido que coinciden con el contenido del video.

curl --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.5-t2v-preview",
        "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 \""
        },
        "parameters": {
            "size": "832*480",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Generar un video silencioso

Solo los modelos de las series wan2.2 y wan2.1 admiten la generación de videos silenciosos. Estos modelos producen videos silenciosos de forma predeterminada sin configuración adicional.

Los modelos de las series wan2.6 y wan2.5 generan videos con audio de forma predeterminada.

curl --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": "Low contrast. In a retro 1970s-style subway station, a street musician plays amidst dim colors and rough textures. He wears an old-fashioned jacket and holds a guitar, playing with concentration. Commuters hurry past, and a small crowd gradually gathers to listen. The camera slowly pans to the right, capturing a scene where the sound of the instrument mixes with the city's noise, with old-fashioned subway signs and mottled walls in the background."
        },
        "parameters": {
            "size": "832*480",
            "prompt_extend": true
        }
    }'

Usar un prompt negativo

Modelos admitidos: Todos los modelos.

Utilice negative_prompt para excluir elementos específicos (como "flowers") del video generado.

curl --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": "A kitten running in the moonlight",
            "negative_prompt": "flowers"
        },
        "parameters": {
            "size": "832*480"
        }
    }'
Encabezados de solicitud

Content-Type string (Requerido)

El tipo de contenido de la solicitud. Debe ser application/json.

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

X-DashScope-Async string (Requerido)

Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser enable.

ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls".

Cuerpo de la solicitud

model string (Obligatorio)

Nombre del modelo. Para modelos y precios, consulte Precios de modelos.

Ejemplo: wan2.6-t2v.

input object (Obligatorio)

Datos de entrada, incluido el prompt.

Propiedades

prompt string (Obligatorio)

Prompt de texto que describe el contenido del video y el estilo visual.

Admite chino e inglés. Cada carácter o letra cuenta como uno. El texto que exceda el límite se trunca automáticamente. Longitud máxima según el modelo:

  • Modelos de las series wan2.6 y wan2.5: Hasta 1,500 caracteres.
  • Modelos de las series wan2.2 y wan2.1: Hasta 800 caracteres.

Ejemplo: Un gatito corriendo bajo la luz de la luna.

Para obtener consejos, consulte la Guía de prompts de texto a video/imagen a video.

negative_prompt string (Opcional)

Elementos a excluir del video generado.

Admite chino e inglés. Máximo de 500 caracteres; el texto más largo se trunca automáticamente.

Ejemplo: baja resolución, error, peor calidad, baja calidad, desfigurado, dedos extra, malas proporciones.

audio_url string (Opcional)

Modelos compatibles: series wan2.6 y wan2.5.

URL del archivo de audio para la generación de video.

Formatos admitidos:

  1. URL pública:

Límites de audio:

  • Formato: WAV, MP3.
  • Duración: de 3 s a 30 s.
  • Tamaño de archivo: Hasta 15 MB.
  • Manejo de duración: Si el audio excede el valor de duration (por ejemplo, 5 s), solo se utilizan los primeros 5 s. Si el audio es más corto que el video, el resto del video permanece en silencio. Por ejemplo, 3 s de audio con un video de 5 s producen 3 s de audio seguidos de 2 s de silencio.

parameters object (Opcional)

Parámetros de generación de video: resolución, reescritura de prompts y marca de agua.

Propiedades

size string (Opcional)

Importante

  • El parámetro size afecta el costo: Costo = Precio unitario (basado en resolución) x Duración (segundos). Para el mismo modelo: 1080p > 720p > 480p. Consulte los precios de modelos.
  • Establezca size en una resolución específica (como 1280*720), no en una relación de aspecto (1:1) ni en una etiqueta de nivel (480p).

Resolución del video de salida en formato width*height. Los valores predeterminados y válidos dependen del modelo:

  • wan2.6-t2v: El valor predeterminado es 1920*1080 (1080p). Resoluciones válidas: todas las de los niveles de 720p y 1080p.
  • wan2.5-t2v-preview: El valor predeterminado es 1920*1080 (1080p). Resoluciones válidas: todas las de los niveles de 480p, 720p y 1080p.
  • wan2.2-t2v-plus: El valor predeterminado es 1920*1080 (1080p). Resoluciones válidas: todas las de los niveles de 480p y 1080p.
  • wan2.1-t2v-turbo: El valor predeterminado es 1280*720 (720p). Resoluciones válidas: todas las de los niveles de 480p y 720p.
  • wan2.1-t2v-plus: El valor predeterminado es 1280*720 (720p). Resoluciones válidas: todas las del nivel de 720p.

Resoluciones y relaciones de aspecto del nivel de 480p:

  • 832*480: 16:9.
  • 480*832: 9:16.
  • 624*624: 1:1.

Resoluciones y relaciones de aspecto del nivel de 720p:

  • 1280*720: 16:9.
  • 720*1280: 9:16.
  • 960*960: 1:1.
  • 1088*832: 4:3.
  • 832*1088: 3:4.

Resoluciones y relaciones de aspecto del nivel de 1080p:

  • 1920*1080: 16:9.
  • 1080*1920: 9:16.
  • 1440*1440: 1:1.
  • 1632*1248: 4:3.
  • 1248*1632: 3:4.

duration integer (Opcional)

ImportanteLa duración afecta el costo: Costo = Precio unitario (basado en resolución) x Duración (segundos). Consulte los precios de modelos.

Duración del video de salida en segundos. Los valores válidos dependen del modelo:

  • wan2.6-t2v: Un entero de 2 a 15. El valor predeterminado es 5.
  • wan2.5-t2v-preview: Los valores válidos son 5 y 10. El valor predeterminado es 5.
  • wan2.2-t2v-plus: Fijo en 5 segundos y no se puede cambiar.
  • wan2.1-t2v-plus: Fijo en 5 segundos y no se puede cambiar.
  • wan2.1-t2v-turbo: Fijo en 5 segundos y no se puede cambiar.

prompt_extendboolean (Opcional)

Habilita la reescritura de prompts. Cuando está habilitado, un LLM reescribe el prompt de entrada para mejorar la calidad. Es ideal para prompts cortos, pero añade latencia.

  • true (predeterminado)
  • false

shot_type string (Opcional)

Modelos admitidos: Modelos wan2.6.

Estructura de tomas para el video de salida: una toma continua o múltiples tomas con transiciones.

Valores válidos:

  • single (predeterminado)
  • multi

Este parámetro solo surte efecto cuando se establece "prompt_extend": true.

Prioridad: shot_type anula el prompt. Establecer shot_type en single produce un video de una sola toma incluso si el prompt solicita múltiples tomas.

watermark boolean (Opcional)

Añade una marca de agua en la esquina inferior derecha con el texto "AI Generated".

  • false (predeterminado)
  • true

seed integer (Opcional)

La semilla de número aleatorio debe ser un entero en el rango [0, 2147483647].

Si no se especifica, se genera una semilla aleatoria. Una semilla fija mejora la reproducibilidad.

Dado que la generación del modelo es probabilística, la misma semilla no garantiza resultados idénticos.

Parámetros de respuesta

Respuesta exitosa

Guarde el task_id para consultar el estado y el resultado de la tarea.

{
    "output": {
        "task_status": "PENDING",
        "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
    },
    "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
}

Respuesta de error

Error en la creación de la tarea. Consulte Códigos de error.

{
    "code": "InvalidApiKey",
    "message": "Invalid API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

output object

Salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

Paso 2: Consultar el resultado

Singapore

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Virginia

GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Beijing

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Fráncfort

GET https:// {WorkspaceId}.eu-central-1.maas.aliyuncs.com /api/v1/tasks/{task_id}

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Nota

  • Recomendación de sondeo: La generación de video tarda varios minutos. Utilice un mecanismo de sondeo con un intervalo razonable, como 15 segundos.
  • Transición de estado de la tarea: PENDING → RUNNING → SUCCEEDED o FAILED.
  • Enlace de resultado: Después de que una tarea tenga éxito, se devuelve una URL de video válida durante 24 horas. Descargue y guarde el video en un almacenamiento permanente, como OSS.
  • task_idvalidez: 24 horas. Después de este período, las consultas devuelven el estado de la tarea como UNKNOWN.

Parámetros de solicitud

Consultar resultado de la tarea

Reemplace {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"
Encabezados

Authorization string (Requerido)

Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx.

Parámetros de ruta

task_id string (Obligatorio)

El ID de la tarea.

Parámetros de respuesta

Tarea ejecutada correctamente

Las URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato.

{
        "request_id": "abbf7aa3-9652-4785-a622-xxxxxx",
        "output": {
            "task_id": "38513c71-5190-48e1-9f3b-xxxxxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2025-09-29 14:05:22.119",
            "scheduled_time": "2025-09-29 14:05:28.278",
            "end_time": "2025-09-29 14:10:00.437",
            "orig_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's 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'.",
            "video_url": "https://dashscope-result-sh.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx"
        },
        "usage": {
            "duration": 10,
            "size": "1280*720",
            "input_video_duration": 0,
            "output_video_duration": 10,
            "video_count": 1,
            "SR": 720
        }
    }

Error en la ejecución de la tarea

Cuando una tarea falla, task_status es FAILED con un código de error y un mensaje. Consulte Códigos de error.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match xxxxxx"
    }
}

Consulta de tarea caducada

El task_id es válido durante 24 horas. Después de este período, las consultas devuelven el siguiente error.

{
    "request_id": "a4de7c32-7057-9f82-8581-xxxxxx",
    "output": {
        "task_id": "502a00b1-19d9-4839-a82f-xxxxxx",
        "task_status": "UNKNOWN"
    }
}

outputobject

Salida de la tarea.

Propiedades

task_id string

El ID de la tarea. Válido para consultas durante 24 horas.

task_status string

El estado de la tarea.

Valores de enumeración

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: La tarea no existe o se desconoce su estado.
Transiciones de estado durante el sondeo:
  • PENDING → RUNNING → SUCCEEDED o FAILED.
  • El estado inicial de la consulta suele ser PENDING o RUNNING.
  • Cuando el estado cambia a SUCCEEDED, la respuesta contiene la URL del video generado.
  • Si el estado es FAILED, revise el mensaje de error y reintente la tarea.

submit_time string

La hora en que se envió la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

La hora en que se ejecutó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

end_time string

La hora en que se completó la tarea. La hora está en UTC+8 y el formato es YYYY-MM-DD HH:mm:ss.SSS.

video_url string

URL del video generado. Se devuelve solo cuando task_status es SUCCEEDED.

Válido durante 24 horas. El video está en formato MP4 con codificación H.264.

orig_prompt string

El prompt de entrada original, correspondiente al parámetro de solicitud prompt.

actual_prompt string

Cuando prompt_extend=true, el sistema reescribe el prompt de entrada. Este campo contiene el prompt reescrito utilizado para la generación.

  • No se devuelve cuando prompt_extend=false.
  • El modelo wan2.6 no devuelve este campo, independientemente del valor de prompt_extend.

code string

Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

message string

Mensaje de error detallado. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error.

usage object

Estadísticas de salida. Se devuelven solo para tareas exitosas.

Propiedades

video_duration integer

Se devuelve solo para wan2.5 y anteriores (utilizado para facturación).

Duración del video de salida en segundos. Valores válidos: 5, 10.

duration float

Se devuelve solo para wan2.6 (utilizado para facturación).

Duración total del video. Fórmula: duration=input_video_duration+output_video_duration.

input_video_duration integer

Se devuelve solo para wan2.6. Valor fijo: 0.

output_video_duration integer

Se devuelve solo para wan2.6.

Duración del video de salida en segundos. Coincide con el valor de input.duration.

SR integer

Se devuelve solo para wan2.6. Nivel de resolución del video de salida. Ejemplo: 720.

size string

Se devuelve solo para wan2.6. Resolución de salida en formato "ancho×alto". Ejemplo: 1920×1080.

video_ratio string

Se devuelve solo para wan2.5 y anteriores. Resolución de salida en formato "ancho×alto". Ejemplo: 832×480.

video_count integer

Número de videos generados. Siempre 1.

request_id string

Identificador único de solicitud para rastreo y solución de problemas.

SDK de DashScope

Los nombres de los parámetros del SDK coinciden en su mayoría con los de la API HTTP, con estructuras que siguen las convenciones específicas del lenguaje.

Las tareas de texto a video tardan entre 1 y 5 minutos. El SDK encapsula el flujo de llamadas HTTP asíncronas y admite tanto la invocación síncrona como la asíncrona.

El tiempo real de procesamiento depende de la profundidad de la cola y la carga del servicio.

SDK de Python

Importante

  • El SDK admite wan2.6 y anteriores. wan2.7 no es compatible.

  • Se requiere la versión 1.25.8 o posterior del SDK de Python de DashScope.

    Las versiones anteriores pueden devolver "url error, please check url!". Para actualizar, consulte Instalar el SDK.

Establezca dashscope.base_http_api_url en el endpoint de la región:

Beijing

dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'

Singapore

dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

Virginia

dashscope.base_http_api_url = 'https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1'

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Invocación síncrona

Ejemplo de solicitud
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os

# URL for the Singapore region. URLs vary by region. For more information, see 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 no environment variable is configured, replace with your Model Studio API key: api_key="sk-xxx".
# API keys vary by region. For more information, see https://www.alibabacloud.com/help/model-studio/get-api-key.
api_key = os.getenv("DASHSCOPE_API_KEY")

def sample_sync_call_t2v():
    # Call the sync API and return the result.
    print('Please wait...')
    rsp = VideoSynthesis.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,
                              negative_prompt="",
                              prompt_extend=True,
                              watermark=False,
                              seed=12345)
    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_sync_call_t2v()
Ejemplo de respuesta

La video_url caduca después de 24 horas. Descárguela pronto.

{
    "status_code": 200,
    "request_id": "167f3beb-3dd0-47fe-a83c-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "5b65411f-d946-4e29-859e-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-bj.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "submit_time": "2025-10-23 11:47:23.879",
        "scheduled_time": "2025-10-23 11:47:34.351",
        "end_time": "2025-10-23 11:52:35.323",
        "orig_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's 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 '."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 0,
        "video_ratio": "",
        "duration": 10,
        "size": "1280*720",
        "input_video_duration": 0,
        "output_video_duration": 10,
        "SR": 720
    }
}

Invocación asíncrona

Ejemplo de solicitud
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os

# This is the Singapore region URL. URLs vary by region. For more information, see: 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 an environment variable is not configured, replace this with your Model Studio API key: api_key="sk-xxx"
# API keys vary by region. For more information, see: https://www.alibabacloud.com/help/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

def sample_async_call_t2v():
    # Call the asynchronous API and return the task information.
    # Use the task ID to check the status.
    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,
                                    negative_prompt="",
                                    prompt_extend=True,
                                    watermark=False,
                                    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))

    # Retrieve the task information, including the task status.
    status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
    if status.status_code == HTTPStatus.OK:
        print(status.output.task_status)  # Check the task status.
    else:
        print('Failed. Status code: %s, code: %s, message: %s' %
              (status.status_code, status.code, status.message))

    # Wait for the task to complete. This method calls fetch at intervals and checks if the task is in a finished state.
    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()
Ejemplo de respuesta
  1. Ejemplo de respuesta de creación de tarea
{
	"status_code": 200,
	"request_id": "c86ff7ba-8377-917a-90ed-xxxxxx",
	"code": "",
	"message": "",
	"output": {
		"task_id": "721164c6-8619-4a35-a6d9-xxxxxx",
		"task_status": "PENDING",
		"video_url": ""
	},
	"usage": null
}
  1. Ejemplo de respuesta de consulta de tarea

    La video_url caduca después de 24 horas. Descárguela pronto.

{
    "status_code": 200,
    "request_id": "167f3beb-3dd0-47fe-a83c-xxxxxx",
    "code": null,
    "message": "",
    "output": {
        "task_id": "5b65411f-d946-4e29-859e-xxxxxx",
        "task_status": "SUCCEEDED",
        "video_url": "https://dashscope-result-bj.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
        "submit_time": "2025-10-23 11:47:23.879",
        "scheduled_time": "2025-10-23 11:47:34.351",
        "end_time": "2025-10-23 11:52:35.323",
        "orig_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's 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 '."
    },
    "usage": {
        "video_count": 1,
        "video_duration": 0,
        "video_ratio": "",
        "duration": 10,
        "size": "1280*720",
        "input_video_duration": 0,
        "output_video_duration": 10,
        "SR": 720
    }
}

SDK de Java

Importante

  • El SDK admite wan2.6 y anteriores. wan2.7 no es compatible.

  • Se requiere la versión 2.22.6 o posterior del SDK de Java de DashScope.

    Las versiones anteriores pueden devolver "url error, please check url!". Para actualizar, consulte Instalar el SDK.

Establezca Constants.baseHttpApiUrl en el endpoint de la región:

Singapore

Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

Virginia

Constants.baseHttpApiUrl = "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";

Beijing

Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";

Reemplace {WorkspaceId} con su ID de espacio de trabajo real.

Invocación síncrona

Ejemplo de solicitud
// Copyright (c) Alibaba, Inc. and its affiliates.

// dashscope SDK version 2.18.2 or later
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;

import java.util.HashMap;
import java.util.Map;

public class Text2Video {

    static {
        // Singapore region URL. URLs vary by region. For more information, see 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 no environment variable is configured, replace the value with your Model Studio API key: apiKey = "sk-xxx".
    // API keys vary by region. For more information, see https://www.alibabacloud.com/help/model-studio/get-api-key.
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void text2Video() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        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)
                        .parameters(parameters)
                        .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);
    }
}
Ejemplo de respuesta

La video_url caduca después de 24 horas. Descárguela pronto.

{
    "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",
        "orig_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 '",
        "submit_time": "2026-01-22 23:13:40.553",
        "scheduled_time": "2026-01-22 23:13:49.415",
        "end_time": "2026-01-22 23:17:56.380"
    },
    "usage": {
        "video_count": 1,
        "duration": 10.0,
        "size": "1280*720",
        "input_video_duration": 0.0,
        "output_video_duration": 10.0,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Invocación asíncrona

Ejemplo de solicitud
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesis;
import com.alibaba.dashscope.aigc.videosynthesis.VideoSynthesisListResult;
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.task.AsyncTaskListParam;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.HashMap;
import java.util.Map;

public class Text2Video {
    static {
        // The URL for the Singapore region. URLs vary by region. For more information, see 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 an environment variable is not set, replace the placeholder with your Model Studio API key, for example: apiKey="sk-xxx"
    // API keys vary by region. For more information, see https://www.alibabacloud.com/help/model-studio/get-api-key
    public static String apiKey = System.getenv("DASHSCOPE_API_KEY");

    public static void text2Video() throws ApiException, NoApiKeyException, InputRequiredException {
        VideoSynthesis vs = new VideoSynthesis();
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", false);
        parameters.put("seed", 12345);

        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)
                        .parameters(parameters)
                        .build();

        // Make an asynchronous call.
        VideoSynthesisResult task = vs.asyncCall(param);
        System.out.println(JsonUtils.toJson(task));
        System.out.println("please wait...");

        // Retrieve the result.
        VideoSynthesisResult result = vs.wait(task, apiKey);
        System.out.println(JsonUtils.toJson(result));
    }

     // Retrieve the task list.
    public static void listTask() throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        param.setApiKey(apiKey);
        VideoSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    // Retrieve the result of a single task.
    public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
        VideoSynthesis is = new VideoSynthesis();
        // If you set the DASHSCOPE_API_KEY environment variable, you can set apiKey to null.
        VideoSynthesisResult result = is.fetch(taskId, apiKey);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args) {
        try {
            text2Video();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}
Ejemplo de respuesta
  1. Ejemplo de respuesta de creación de tarea.
{
        "request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}
  1. Ejemplo de respuesta de consulta de tarea

    La video_url caduca después de 24 horas. Descárguela pronto.

{
    "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",
        "orig_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 '",
        "submit_time": "2026-01-22 23:13:40.553",
        "scheduled_time": "2026-01-22 23:13:49.415",
        "end_time": "2026-01-22 23:17:56.380"
    },
    "usage": {
        "video_count": 1,
        "duration": 10.0,
        "size": "1280*720",
        "input_video_duration": 0.0,
        "output_video_duration": 10.0,
        "SR": "720"
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

Limitaciones

  • Retención de datos: El ID de tarea (task_id) y la URL del video (video_url) caducan después de 24 horas. Tras la caducidad, no se pueden consultar ni descargar.
  • Moderación de contenido: La entrada y la salida pasan por moderación de contenido. El contenido prohibido activa errores "IPInfringementSuspect" o "DataInspectionFailed". Consulte Códigos de error.

Códigos de error

Si la llamada al modelo falla y devuelve un mensaje de error, consulte Códigos de error para su resolución.

FAQ

P: ¿Qué cambios de código se necesitan para actualizar de wan2.6 a wan2.7?

R: Se requieren dos cambios:

  • Control de resolución: wan2.7 reemplaza el campo size. En su lugar, utiliza una combinación de resolution (nivel de resolución) y ratio (relación de aspecto) para definir la resolución de salida. Los modelos anteriores utilizaban el campo size.
  • Eliminación del tipo de toma: wan2.7 elimina el campo shot_type. Describa la estructura de las tomas directamente en el prompt.

P: ¿Cómo convierto un enlace de video temporal en uno permanente?

R: La conversión directa no es posible. Descargue el video desde la URL y luego súbalos a un almacenamiento persistente (como Alibaba Cloud OSS) para generar un enlace permanente.

Código de ejemplo: Descargar un video a un dispositivo local

import requests

def download_and_save_video(video_url, save_path):
    try:
        response = requests.get(video_url, stream=True, timeout=300)
        response.raise_for_status()
        with open(save_path, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        print(f"Video successfully downloaded to: {save_path}")
        # You can add logic to upload the video to permanent storage here
    except requests.exceptions.RequestException as e:
        print(f"Failed to download video: {e}")

if __name__ == '__main__':
    video_url = "http://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxxx"
    save_path = "video.mp4"
    download_and_save_video(video_url, save_path)

P: ¿Se puede reproducir directamente en un navegador el enlace de video devuelto?

R: No. El enlace caduca después de 24 horas. Descargue el video, almacénelo de forma persistente y utilice un enlace permanente para su reproducción.