O modelo de texto para vídeo Wan gera vídeos fluidos a partir de prompts de texto.
Referências: Guia do usuário
Disponibilidade
A região do seu modelo, a URL do endpoint e a chave de API devem corresponder. Chamadas entre regiões falham.
- Selecione um modelo: Acesse Model Gallery para selecionar um modelo e verificar sua região.
- Selecione uma URL: Use a URL do endpoint para a região correspondente. HTTP e HTTPS são suportados.
- Configurar uma chave de API: Selecione uma região, obtenha uma chave de API e configure-a nas variáveis de ambiente.
- Instalar o SDK: Para chamar a API por meio de um SDK, instale o SDK do DashScope.
ObservaçãoO código de exemplo neste tópico usa a região de Singapura.
ImportanteO Alibaba Cloud Model Studio lançou domínios específicos para espaços de trabalho nas regiões da China (Pequim) e Singapura. Os novos domínios dedicados oferecem desempenho superior e maior estabilidade para solicitações de inferência. Recomendamos a migração para os novos domínios:
- China (Pequim): de
https://dashscope.aliyuncs.comparahttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapura: de
https://dashscope-intl.aliyuncs.comparahttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} é o seu ID do espaço de trabalho, que pode ser encontrado na página Workspace Details no console do Alibaba Cloud Model Studio. O domínio existente permanece totalmente funcional.
HTTP (wan2.7)
ImportanteEsta interface usa o novo protocolo e suporta apenas wan2.7.
As tarefas de texto para vídeo levam de 1 a 5 minutos. A API usa invocação assíncrona: Criar uma tarefa → Consultar o resultado.
Etapa 1: Criar uma tarefa
Pequim
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
Pequim
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Observação
- Após a criação da tarefa, use o
task_idretornado para consultar o resultado. Otask_idé válido por 24 horas. Não crie tarefas duplicadas. Em vez disso, use polling para recuperar o resultado. - Para orientações para iniciantes, consulte Chamar APIs com Postman ou cURL.
Parâmetros de solicitação | Narrativa de múltiplos planosControle a estrutura de planos com linguagem natural no
Fornecer um arquivo de áudioEspecifique uma URL de arquivo de áudio personalizada no parâmetro Dublagem automáticaSem Usar um prompt negativoUse negative_prompt para excluir o elemento "flor" e impedir que ele apareça no vídeo. dashscope CLIChamada via linha de comando do dashscope. ImportanteO assistente interativo SDK Expert pode realizar o mesmo desenvolvimento e solução de problemas por meio de linguagem natural, consulte DashScope SDK Expert.Para a tabela completa de regiões, consulte Visão geral da URL base. |
Cabeçalhos | |
Content-Type O tipo de conteúdo da requisição. Deve ser | |
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
X-DashScope-Async Habilita o processamento assíncrono. Requisições HTTP suportam apenas chamadas assíncronas. Deve ser ImportanteSe este cabeçalho de solicitação estiver ausente, o erro "a API do usuário atual não suporta chamadas síncronas" será retornado. | |
Corpo da requisição | |
model Nome do modelo. Para modelos e preços, consulte Preços dos modelos. Exemplo: wan2.7-t2v, wan2.7-t2v-2026-06-12. | |
input Dados de entrada, incluindo o prompt. | |
parameters Parâmetros de geração de vídeo: resolução, reescrita de prompt e marca d'água. |
Parâmetros de resposta | Resposta bem-sucedidaSalve o Resposta de erroFalha na criação da tarefa. Consulte Códigos de erro. |
output Saída da tarefa. | |
request_id Identificador exclusivo da requisição para rastreamento e solução de problemas. | |
code Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro. | |
message Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro. |
Etapa 2: Consultar o resultado
Pequim
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}
Pequim
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Observação
- Recomendação de polling: A geração de vídeo leva vários minutos. Use um mecanismo de polling com um intervalo razoável, como 15 segundos.
- Transição de estado da tarefa: PENDING → RUNNING → SUCCEEDED ou FAILED.
- Link do resultado: Após o sucesso de uma tarefa, uma URL de vídeo válida por 24 horas é retornada. Baixe e salve o vídeo em um armazenamento permanente, como o OSS.
task_idvalidade: 24 horas. Após esse período, as consultas retornam o status da tarefa comoUNKNOWN.
Parâmetros de solicitação | Consultar resultado da tarefaSubstitua |
Cabeçalhos | |
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
Parâmetros de caminho | |
task_id O ID da tarefa. |
Parâmetros de resposta | Tarefa executada com sucessoAs URLs de vídeo são válidas por apenas 24 horas e depois são removidas automaticamente. Salve os vídeos gerados prontamente. Falha na execução da tarefaQuando uma tarefa falha, Consulta da tarefa expiradaO |
output Saída da tarefa. | |
usage Estatísticas de saída. Retornado apenas para tarefas bem-sucedidas. | |
request_id Identificador exclusivo da requisição para rastreamento e solução de problemas. |
HTTP (wan2.6 e anteriores)
ImportanteEsta interface usa o protocolo legado e suporta wan2.6 e anteriores (wan2.5/wan2.2/wan2.1).
As tarefas de texto para vídeo levam de 1 a 5 minutos, portanto a API usa invocação assíncrona: Criar uma tarefa → Consultar o resultado.
Etapa 1: Criar uma tarefa
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Virgínia
POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Pequim
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Frankfurt
POST https:// {WorkspaceId}.eu-central-1.maas.aliyuncs.com/ api/v1/services/aigc/video-generation/video-synthesis
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Observação
- Após a criação da tarefa, use o
task_idretornado para consultar o resultado. Otask_idé válido por 24 horas. Não crie tarefas duplicadas. Em vez disso, use polling para recuperar o resultado. - Para orientações para iniciantes, consulte Chamar APIs com Postman ou cURL.
Parâmetros de solicitação | Narrativa de múltiplos planos
Passar um arquivo de áudioModelos suportados: séries wan2.6 e wan2.5. Defina o parâmetro Dublagem automáticaModelos suportados: séries wan2.6 e wan2.5. Sem o parâmetro Gerar um vídeo sem somApenas os modelos das séries wan2.2 e wan2.1 suportam a geração de vídeos sem som. Esses modelos produzem vídeos sem som por padrão, sem configuração adicional.
Usar um prompt negativoModelos suportados: Todos os modelos. Use negative_prompt para excluir elementos específicos (como "flores") do vídeo gerado. |
Cabeçalhos da requisição | |
Content-Type O tipo de conteúdo da requisição. Deve ser | |
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
X-DashScope-Async Habilita o processamento assíncrono. Requisições HTTP suportam apenas chamadas assíncronas. Deve ser ImportanteSe este cabeçalho de solicitação estiver ausente, o erro "a API do usuário atual não suporta chamadas síncronas" será retornado. | |
Corpo da requisição | |
model Nome do modelo. Para modelos e preços, consulte Preços dos modelos. Exemplo: wan2.6-t2v. | |
input Dados de entrada, incluindo o prompt. | |
parameters Parâmetros de geração de vídeo: resolução, reescrita de prompt e marca d'água. |
Parâmetros de resposta | Resposta bem-sucedidaSalve o Resposta de erroFalha na criação da tarefa. Consulte Códigos de erro. |
output Saída da tarefa. | |
request_id Identificador exclusivo da requisição para rastreamento e solução de problemas. | |
code Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro. | |
message Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro. |
Etapa 2: Consultar o resultado
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Virgínia
GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Pequim
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Frankfurt
GET https:// {WorkspaceId}.eu-central-1.maas.aliyuncs.com /api/v1/tasks/{task_id}
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Observação
- Recomendação de polling: A geração de vídeo leva vários minutos. Use um mecanismo de polling com um intervalo razoável, como 15 segundos.
- Transição de estado da tarefa: PENDING → RUNNING → SUCCEEDED ou FAILED.
- Link do resultado: Após o sucesso de uma tarefa, uma URL de vídeo válida por 24 horas é retornada. Baixe e salve o vídeo em um armazenamento permanente, como o OSS.
task_idvalidade: 24 horas. Após esse período, as consultas retornam o status da tarefa comoUNKNOWN.
Parâmetros de solicitação | Consultar resultado da tarefaSubstitua |
Cabeçalhos | |
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. | |
Parâmetros de caminho | |
task_id O ID da tarefa. |
Parâmetros de resposta | Tarefa executada com sucessoAs URLs de vídeo são válidas por apenas 24 horas e depois são removidas automaticamente. Salve os vídeos gerados prontamente. Falha na execução da tarefaQuando uma tarefa falha, Consulta da tarefa expiradaO |
output Saída da tarefa. | |
usage Estatísticas de saída. Retornado apenas para tarefas bem-sucedidas. | |
request_id Identificador exclusivo da requisição para rastreamento e solução de problemas. |
DashScope SDK
Os nomes dos parâmetros do SDK correspondem principalmente à API HTTP, com estruturas seguindo as convenções específicas de cada linguagem.
As tarefas de texto para vídeo levam de 1 a 5 minutos. O SDK encapsula o fluxo de chamadas HTTP assíncronas e suporta invocação síncrona e assíncrona.
O tempo real de processamento depende da profundidade da fila e da carga do serviço.
Python SDK
Importante
-
O SDK suporta wan2.6 e anteriores. wan2.7 não é suportado.
-
É necessária a versão 1.25.8 ou posterior do DashScope Python SDK.
Versões mais antigas podem retornar "url error, please check url!". Para atualizar, consulte Instalar o SDK.
Defina region de acordo com a região do modelo (passada ao construir o Client; o valor de region varia conforme a região):
Pequim
region="cn-beijing"
Singapore
region="ap-southeast-1"
Virgínia
region="us-east-1"
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Invocação síncrona
Exemplo de solicitação
import dashscope
import os
from dashscope.v2 import DashScopeError
# A configuração abaixo refere-se à região Singapura (ap-southeast-1). Substitua {WorkspaceId} pelo ID real do seu workspace. O valor de region varia conforme a região.
client = dashscope.Client(
# Se a variável de ambiente não estiver configurada, substitua a linha a seguir pela sua API Key do Model Studio: api_key="sk-xxx"
# As API Keys são específicas de cada região. Para obter uma API Key, consulte https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
def sample_sync_call_t2v():
# generate é uma chamada de uma etapa (envia a tarefa e aguarda a conclusão) e retorna um Job concluído
print('Please wait...')
try:
# audio_url e negative_prompt são campos da seção input, não estão na assinatura nomeada; passe-os através de extra_input.
job = client.videos.generate(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.'",
extra_input={'audio_url': 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3',
'negative_prompt': ""},
size='1280*720',
duration=10,
prompt_extend=True,
watermark=False,
seed=12345)
print(job)
print(job.video_url)
except DashScopeError as e:
print(f"HTTP status code: {e.status_code}")
print(f"Error code: {e.code}")
print(f"Error message: {e.message}")
print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
if __name__ == '__main__':
sample_sync_call_t2v()
Exemplo de resposta
O video_url expira após 24 horas. Faça o download imediatamente.
{
"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
}
}
Invocação assíncrona
Exemplo de solicitação
import dashscope
import os
from dashscope.v2 import DashScopeError
# A configuração abaixo refere-se à região Singapura (ap-southeast-1). Substitua {WorkspaceId} pelo ID real do seu workspace. O valor de region varia conforme a região.
client = dashscope.Client(
# Se a variável de ambiente não estiver configurada, substitua a linha a seguir pela sua API Key do Model Studio: api_key="sk-xxx"
# As API Keys são específicas de cada região. Para obter uma API Key, consulte https://www.alibabacloud.com/help/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
def sample_async_call_t2v():
# Call the asynchronous API and return the task information.
# Use the task ID to check the status.
try:
# audio_url e negative_prompt são campos da seção input, não estão na assinatura nomeada; passe-os através de extra_input.
job = client.videos.jobs.create(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 '.",
extra_input={'audio_url': 'https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3',
'negative_prompt': ""},
size='1280*720',
duration=10,
prompt_extend=True,
watermark=False,
seed=12345)
print(job)
print("task_id: %s" % job.task_id)
except DashScopeError as e:
print(f"HTTP status code: {e.status_code}")
print(f"Error code: {e.code}")
print(f"Error message: {e.message}")
print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
return
# Retrieve the task information, including the task status.
try:
snapshot = client.videos.jobs.fetch(job.task_id)
print(snapshot.status) # check the task status
except DashScopeError as e:
print(f"HTTP status code: {e.status_code}")
print(f"Error code: {e.code}")
print(f"Error message: {e.message}")
print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
# Wait for the task to complete. This method calls fetch at intervals and checks if the task is in a finished state.
# (jobs.wait in SDK 2.0 uses exponential backoff polling, with a default total budget of 24 hours; a FAILED task raises an exception.)
try:
done = client.videos.jobs.wait(job)
print(done)
print(done.video_url)
except DashScopeError as e:
print(f"HTTP status code: {e.status_code}")
print(f"Error code: {e.code}")
print(f"Error message: {e.message}")
print("See the documentation: https://www.alibabacloud.com/help/model-studio/developer-reference/error-code")
if __name__ == '__main__':
sample_async_call_t2v()
Exemplo de resposta
- Exemplo de resposta de criação de tarefa
{
"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
}
-
Exemplo de resposta de consulta de tarefa
O video_url expira após 24 horas. Faça o download imediatamente.
{
"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
}
}
Java SDK
Importante
-
O SDK suporta wan2.6 e anteriores. wan2.7 não é suportado.
-
É necessária a versão 2.22.6 ou posterior do DashScope Java SDK.
Versões mais antigas podem retornar "url error, please check url!". Para atualizar, consulte Instalar o SDK.
Defina Constants.baseHttpApiUrl para o endpoint da região:
Singapore
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
Virgínia
Constants.baseHttpApiUrl = "https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1";
Pequim
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
Substitua {WorkspaceId} pelo seu ID do espaço de trabalho.
Invocação síncrona
Exemplo de solicitação
// 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);
}
}
Exemplo de resposta
O video_url expira após 24 horas. Faça o download imediatamente.
{
"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": ""
}
Invocação assíncrona
Exemplo de solicitação
// 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);
}
}
Exemplo de resposta
- Exemplo de resposta de criação de tarefa.
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-xxxxxxxx",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}
-
Exemplo de resposta de consulta de tarefa
O video_url expira após 24 horas. Faça o download imediatamente.
{
"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": ""
}
Limitações
- Retenção de dados: O ID da tarefa (
task_id) e a URL do vídeo (video_url) expiram após 24 horas. Após a expiração, eles não podem ser consultados ou baixados. - Moderação de conteúdo: A entrada e a saída passam por moderação de conteúdo. Conteúdo proibido aciona erros "IPInfringementSuspect" ou "DataInspectionFailed". Consulte Códigos de erro.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.
FAQ
P: Quais alterações de código são necessárias para atualizar de wan2.6 para wan2.7?
R: Duas alterações são necessárias:
- Controle de resolução: wan2.7 substitui o campo
size. Em vez disso, usa uma combinação deresolution(nível de resolução) eratio(proporção de tela) para definir a resolução de saída. Modelos anteriores usavam o camposize. - Remoção do tipo de plano: wan2.7 remove o campo
shot_type. Em vez disso, descreva a estrutura de planos diretamente no prompt.
P: Como converto um link de vídeo temporário em um permanente?
R: A conversão direta não é possível. Baixe o vídeo da URL e faça o upload para um armazenamento persistente (como o Alibaba Cloud OSS) para gerar um link permanente.
Código de exemplo: Baixar um vídeo para um 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: O link de vídeo retornado pode ser reproduzido diretamente em um navegador?
R: Não. O link expira após 24 horas. Baixe o vídeo, armazene-o de forma persistente e use um link permanente para reprodução.