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.
- Seleccionar un modelo: Confirm la región del modelo.
- Seleccionar una URL: Elija la URL de Endpoint regional correspondiente. Se admiten URLs HTTP y URLs del SDK de DashScope.
- Configurar una clave de API: Seleccione una región, obtenga una clave de API y luego configure la clave de API como variable de entorno (se desaprobará y se fusionará en la configuración de la clave de API).
- Instalar el SDK: Para realizar llamadas mediante el SDK, debe instalar el SDK de DashScope.
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.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
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_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 solicitudEncabezados de solicitudContent-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 solicitudmodel El nombre del modelo a utilizar. Para ver una lista de modelos disponibles, consulte la lista de modelos. Ejemplo: wan2.6-t2v. input Contiene información básica de entrada, como el prompt. parameters Parámetros de procesamiento de video, como configurar la resolución del video, habilitar la reescritura de prompts y agregar una marca de agua. | Narrativa de múltiples tomas
Proporcionar un archivo de audioModelos admitidos: Modelos de la serie wan2.6/wan2.5. Puede proporcionar la URL de un archivo de audio personalizado mediante el parámetro Doblaje automáticoModelos admitidos: Modelos de la serie wan2.6/wan2.5. Si no proporciona Generar un video silenciosoSolo 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.
Usar un prompt negativoModelos admitidos: Todos los modelos. Utilice el parámetro negative_prompt para excluir el elemento "flor" y evitar que aparezca en el video. |
Parámetros de respuestaoutput Contiene la información de 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. | Respuesta exitosaGuarde el Respuesta de errorError en la creación de la tarea. Consulte Códigos de error. |
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 comoUNKNOWN.
Parámetros de solicitudEncabezados de solicitudAuthorization Autentica la solicitud con una clave API de Model Studio. Ejemplo: Bearer sk-xxxx. Parámetros de ruta de URLtask_id El ID de la tarea. | Consultar resultado de la tareaReemplace |
Parámetros de respuestaoutput Contiene la información de salida de la tarea. usage Contiene estadísticas sobre la salida. Esta información se proporciona únicamente para tareas exitosas. request_id Identificador único de solicitud para rastreo y solución de problemas. | Tarea exitosaLas URL de video son válidas solo durante 24 horas y luego se eliminan automáticamente. Guarde los videos generados de inmediato. Tarea fallidaCuando una tarea falla, Consulta de tarea caducadaEl |
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
- 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
}
- 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
- 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"
}
}
- 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.