Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Referencia de la API de texto a video de Wan (2.1-2.6)

Ú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

Para garantizar llamadas exitosas, el modelo, la URL de Endpoint y la API Key deben pertenecer todos a la misma región. Las llamadas entre regiones fallarán.

NotaEl código de ejemplo en este tema aplica a 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

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

Debido a que las tareas de texto a video tardan mucho tiempo (generalmente de 1 a 5 minutos), la API utiliza invocación asíncrona. Todo el proceso implica dos pasos principales: Crear una tarea -> Sondear el resultado. El proceso es el siguiente:

Paso 1: Crear una tarea y obtener el ID de tarea

Singapore

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

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

Virginia

POST https://{WorkspaceId}.us-east-1.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.

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

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)

El nombre del modelo a utilizar. Para ver una lista de modelos disponibles, consulte la lista de modelos.

Ejemplo: wan2.6-t2v.

input object (Obligatorio)

Contiene información básica de entrada, como el prompt.

Propiedades

prompt string (Obligatorio)

El prompt de texto. Describe los elementos deseados y las características visuales del video generado.

El prompt puede estar en chino o en inglés. La longitud se mide en caracteres, donde cada carácter chino o letra cuenta como un carácter. El texto que supere el límite de caracteres se trunca automáticamente. El límite de longitud varía según la versión del 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 más información, consulte la Guía de prompts de texto a video/imagen a video.

negative_prompt string (Opcional)

Un prompt que describe el contenido a excluir del video. Esto ayuda a refinar el contenido generado.

El prompt puede estar en chino o en inglés. La longitud máxima es de 500 caracteres. El texto que supere este límite se truncará automáticamente.

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

audio_url string (Opcional)

Modelos admitidos: modelos de las series wan2.6 y wan2.5.

La URL del archivo de audio. El modelo utilizará este audio para generar el video.

Formatos de entrada admitidos:

  1. URL pública:

Límites de audio:

  • Formato: wav, mp3.
  • Duración: 3 a 30 s.
  • Tamaño de archivo: Hasta 15 MB.
  • Manejo de audio que excede la duración especificada: Si el audio es más largo que el valor especificado para el parámetro duration (por ejemplo, 5 segundos), el audio se trunca a la duración especificada. Si el audio es más corto que la duración del video, la parte restante del video queda en silencio. Por ejemplo, si el audio dura 3 segundos y el video dura 5 segundos, los primeros 3 segundos del video tendrán audio y los últimos 2 segundos estarán en silencio.

parameters object (Opcional)

Parámetros de procesamiento de video, como configurar la resolución del video, habilitar la reescritura de prompts y agregar una marca de agua.

Propiedades

size string (Opcional)

Importante

  • El tamaño afecta directamente al costo. Antes de realizar una llamada, revise los precios de modelos.
  • El tamaño debe establecerse en un valor específico, como 1280*720, no en una relación de aspecto como 1:1 ni en un nivel de resolución como 480P.

Especifica la resolución del video generado en formato width*height. El valor predeterminado y los valores válidos para este parámetro dependen del parámetro model, como se describe a continuación:

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

Nivel 480P: Las resoluciones de video válidas y sus relaciones de aspecto correspondientes son:

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

Nivel 720P: Las resoluciones de video válidas y sus relaciones de aspecto correspondientes son:

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

Nivel 1080P: Las resoluciones de video válidas y sus relaciones de aspecto correspondientes son:

  • 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 directamente al costo. Costo = Precio unitario (basado en la resolución) × Duración (en segundos). Antes de realizar una llamada, revise los precios de modelos.

La duración del video generado en segundos. Los valores válidos para este parámetro dependen del parámetro model:

  • 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)

Especifica si se debe habilitar la reescritura de prompts. Cuando está habilitada, un modelo reescribe inteligentemente el prompt de entrada. Esto mejora significativamente la calidad del video generado para prompts más cortos, pero aumenta el tiempo de ejecución.

  • true (predeterminado)
  • false

shot_type string (Opcional)

Modelos admitidos: Modelos wan2.6.

Especifica el tipo de toma del video generado, es decir, si el video consiste en una sola toma continua o en múltiples tomas cambiantes.

Valores válidos:

  • single: Valor predeterminado. Genera un video de una sola toma.
  • multi: Genera un video de múltiples tomas.

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

Prioridad de parámetros: shot_type > prompt. Por ejemplo, si shot_type se establece en "single", el modelo genera un video de una sola toma incluso si el prompt contiene "generar un video de múltiples tomas".

watermark boolean (Opcional)

Especifica si se debe agregar una marca de agua. La marca de agua se coloca en la esquina inferior derecha del video con el texto fijo "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.

Narrativa de múltiples tomas

  • Para un video de múltiples tomas, shot_type debe establecerse en "multi".
  • Para un video de múltiples tomas, prompt_extend debe establecerse en true para habilitar la reescritura de prompts con el fin de optimizar la descripción de las tomas.

# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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"
    }
}'

Proporcionar un archivo de audio

Modelos admitidos: Modelos de la serie wan2.6/wan2.5.

Puede proporcionar la URL de un archivo de audio personalizado mediante el parámetro input.audio_url.


# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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 admitidos: Modelos de la serie wan2.6/wan2.5.

Si no proporciona input.audio_url, el modelo genera automáticamente música de fondo o efectos de sonido acordes basados en el contenido del video.


# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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 generan videos silenciosos de forma predeterminada y no se requiere configuración adicional.

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


# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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 70s-style subway station, a street musician plays amidst dim colors and rough textures. He wears an old-fashioned jacket, holds a guitar, and plays with concentration. Commuters hurry by, and a small crowd gradually gathers to listen. The camera slowly moves to the right, capturing the scene where the sound of the instrument intertwines with the city's hustle and bustle, with old-style 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 el parámetro negative_prompt para excluir el elemento "flor" y evitar que aparezca en el video.


# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
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": "flower"
    },
    "parameters": {
        "size": "832*480"
    }
}'

Parámetros de respuesta

output object

Contiene la información de 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.

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"
}

Paso 2: Consultar el resultado por ID de tarea

Singapore

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

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

Virginia

GET https://{WorkspaceId}.us-east-1.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.

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

Encabezados de solicitud

Authorization string (Requerido)

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

Parámetros de ruta de URL

task_id string (Obligatorio)

El ID de la tarea.

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"

Parámetros de respuesta

outputobject

Contiene la información de 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 devuelve el prompt optimizado utilizado para la generación.

  • Si prompt_extend=false, este campo no se devuelve.
  • Nota: 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

Contiene estadísticas sobre la salida. Esta información se proporciona únicamente para tareas exitosas.

Propiedades

video_duration integer

Se devuelve solo cuando se utilizan modelos wan2.5 y anteriores. Se usa para facturación.

La duración del video generado en segundos. Los valores válidos son 5 y 10.

duration float

Se devuelve solo cuando se utiliza el modelo wan2.6. Se usa para facturación.

Indica la duración total del video, donde duration = input_video_duration + output_video_duration.

input_video_duration integer

Se devuelve solo cuando se utiliza el modelo wan2.6. Fijo en 0.

output_video_duration integer

Se devuelve solo cuando se utiliza el modelo wan2.6.

La duración del video de salida en segundos. Su valor es el mismo que el valor de input.duration.

SR integer

Se devuelve solo cuando se utiliza el modelo wan2.6. El nivel de resolución del video generado. Ejemplo: 720.

size string

Se devuelve solo cuando se utiliza el modelo wan2.6. La resolución del video generado. El formato es "anchoalto". Ejemplo: 19201080.

video_ratio string

Se devuelve solo cuando se utilizan modelos wan2.5 y anteriores. La resolución del video generado. El formato es "anchoalto". Ejemplo: 832480.

video_count integer

El número de videos generados. Fijo en 1.

request_id string

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

Tarea exitosa

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
    }
}

Tarea fallida

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"
    }
}

SDK de DashScope

Los nombres de los parámetros en el SDK son mayormente consistentes con los de la API HTTP, y la estructura de parámetros está encapsulada para alinearse con las características del lenguaje de programación.

Dado que las tareas de texto a video pueden tardar mucho tiempo en completarse (generalmente de 1 a 5 minutos), el SDK encapsula el proceso de llamada asíncrona HTTP y admite métodos de invocación tanto síncronos como asíncronos.

El tiempo real de procesamiento depende del número de tareas en la cola y del estado del servicio. Espere el resultado.

Python

ImportanteAsegúrese de que su versión del SDK de Python de DashScope sea al menos1.25.16 antes de ejecutar el siguiente código.

Si utiliza una versión anterior, puede encontrar errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.

Establezca dashscope.base_http_api_url según la región donde se encuentra el modelo:

Singapore

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

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

Virginia

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

Beijing

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

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

Fráncfort

dashscope.base_http_api_url = 'https://{WorkspaceId}.eu-central-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. Replace {WorkspaceId} with your actual workspace ID. 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 es válida durante 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,
        "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. Replace {WorkspaceId} with your actual workspace ID. 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 a una solicitud 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 a una solicitud de consulta de tarea

La URL del video caduca en 24 horas. Descargue el video antes de que caduque.

{
    "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,
        "duration": 10,
        "size": "1280*720",
        "input_video_duration": 0,
        "output_video_duration": 10,
        "SR": 720
    }
}

Java

ImportanteAsegúrese de que su versión del kit de desarrollo de software (SDK) de Java de DashScope sea al menos2.22.14 antes de ejecutar el siguiente código.

Si utiliza una versión anterior, puede encontrar errores como "url error, please check url!". Para actualizar el SDK, consulte Instalar el SDK.

Establezca Constants.baseHttpApiUrl según la región donde se encuentra el modelo:

Singapore

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

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

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.

Fráncfort

Constants.baseHttpApiUrl = "https://{WorkspaceId}.eu-central-1.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. Replace {WorkspaceId} with your actual workspace ID. 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 es válida durante 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,
        "output_video_duration": 10,
        "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. Replace {WorkspaceId} with your actual workspace ID. 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 a una solicitud 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 a una solicitud de consulta de tarea

La video_url es válida durante 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,
        "output_video_duration": 10,
        "SR": 720
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

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: ¿Cómo convierto un enlace de video temporal en uno permanente?

R: No puede convertir el enlace directamente. El procedimiento correcto es hacer que su servicio backend recupere la URL, descargue el archivo de video y luego lo cargue en un servicio de almacenamiento de objetos permanente, como Alibaba Cloud Object Storage Service (OSS), para generar un nuevo enlace de acceso 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) # Set a timeout
        response.raise_for_status() # Raise an exception if the HTTP status code is not 200
        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}")
        # Add the logic to upload to permanent storage here
    except requests.exceptions.RequestException as e:
        print(f"Failed to download the 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. No debe reproducir el enlace directamente en un navegador porque caduca después de 24 horas. En su lugar, debe descargar y almacenar el video, y luego utilizar un enlace permanente para su reproducción.