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.
- Seleccionar un modelo: Vaya a Model Gallery para seleccionar un modelo y verificar su región.
- Seleccionar una URL: Utilice la URL de endpoint correspondiente a la región. Se admiten tanto HTTP como HTTPS.
- Configurar una clave de API: Seleccione una región, obtenga una clave de API y configúrela en variables de entorno.
- Instalar el SDK: Para llamar a la API mediante un SDK, instale el SDK de DashScope.
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.comahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapur: de
https://dashscope-intl.aliyuncs.comahttps://{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_iddevuelto para consultar el resultado. Eltask_ides 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 tomasControle la estructura de tomas con lenguaje natural en el
Proporcionar un archivo de audioEspecifique una URL de archivo de audio personalizada en el parámetro Doblaje automáticoSin Usar un prompt negativoUtilice negative_prompt para excluir el elemento "flower" y evitar que aparezca en el video. CLI de dashscopeLlamada a través de la línea de comandos dashscope. 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 El tipo de contenido de la solicitud. Debe ser | |
Authorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. | |
X-DashScope-Async Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls". | |
Cuerpo de la solicitud | |
model Nombre del modelo. Para modelos y precios, consulte Precios de modelos. Ejemplo: wan2.7-t2v, wan2.7-t2v-2026-06-12. | |
input Datos de entrada, incluido el prompt. | |
parameters Parámetros de generación de video: resolución, reescritura de prompts y marca de agua. |
Parámetros de respuesta | Respuesta exitosaGuarde el Respuesta de errorError en la creación de la tarea. Consulte Códigos de error. |
output Salida de la tarea. | |
request_id Identificador único de solicitud para rastreo y solución de problemas. | |
code Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error. | |
message 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 comoUNKNOWN.
Parámetros de solicitud | Consultar resultado de la tareaReemplace |
Encabezados | |
Authorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. | |
Parámetros de ruta | |
task_id El ID de la tarea. |
Parámetros de respuesta | Tarea ejecutada correctamenteLas URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato. Error en la ejecución de la tareaCuando una tarea falla, Consulta de tarea caducadaEl |
output Salida de la tarea. | |
usage Estadísticas de salida. Se devuelven solo para tareas exitosas. | |
request_id 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_iddevuelto para consultar el resultado. Eltask_ides 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
Pasar un archivo de audioModelos compatibles: series wan2.6 y wan2.5. Establezca el parámetro Doblaje automáticoModelos compatibles: series wan2.6 y wan2.5. Sin el parámetro Generar un video silenciosoSolo 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.
Usar un prompt negativoModelos admitidos: Todos los modelos. Utilice negative_prompt para excluir elementos específicos (como "flowers") del video generado. |
Encabezados de solicitud | |
Content-Type El tipo de contenido de la solicitud. Debe ser | |
Authorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. | |
X-DashScope-Async Habilita el procesamiento asíncrono. Las solicitudes HTTP solo admiten llamadas asíncronas. Debe ser ImportanteSi falta este encabezado de solicitud, se devuelve el error "current user api does not support synchronous calls". | |
Cuerpo de la solicitud | |
model Nombre del modelo. Para modelos y precios, consulte Precios de modelos. Ejemplo: wan2.6-t2v. | |
input Datos de entrada, incluido el prompt. | |
parameters Parámetros de generación de video: resolución, reescritura de prompts y marca de agua. |
Parámetros de respuesta | Respuesta exitosaGuarde el Respuesta de errorError en la creación de la tarea. Consulte Códigos de error. |
output Salida de la tarea. | |
request_id Identificador único de solicitud para rastreo y solución de problemas. | |
code Código de error. Se devuelve solo para solicitudes fallidas. Consulte Códigos de error. | |
message 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 comoUNKNOWN.
Parámetros de solicitud | Consultar resultado de la tareaReemplace |
Encabezados | |
Authorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. | |
Parámetros de ruta | |
task_id El ID de la tarea. |
Parámetros de respuesta | Tarea ejecutada correctamenteLas URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato. Error en la ejecución de la tareaCuando una tarea falla, Consulta de tarea caducadaEl |
output Salida de la tarea. | |
usage Estadísticas de salida. Se devuelven solo para tareas exitosas. | |
request_id 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
- 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
}
-
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
- 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"
}
}
-
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 deresolution(nivel de resolución) yratio(relación de aspecto) para definir la resolución de salida. Los modelos anteriores utilizaban el camposize. - 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.