Todos os produtos
Search
Central de documentação

Alibaba Cloud Model Studio:Wan2.7 - referência da API de texto para vídeo

Última atualização: Oct 27, 2026

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.

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.com para https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com
  • Singapura: de https://dashscope-intl.aliyuncs.com para https://{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_id retornado para consultar o resultado. O task_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

Controle a estrutura de planos com linguagem natural no prompt. O parâmetro shot_type não tem efeito.

  • Plano único: Insira "Gere um vídeo de plano único".
  • Múltiplos planos: Insira "Gere um vídeo de múltiplos planos" ou descreva os planos com marcas de tempo (por exemplo, "Plano 1 [0–3 segundos] plano aberto: Rua chuvosa de Nova York à noite").
  • Padrão: Se não especificado, o modelo interpreta o conteúdo de prompt.
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.7-t2v-2026-06-12",
        "input": {
            "prompt": "A tense detective story with cinematic storytelling. Shot 1 [0–3 seconds] wide shot: Rainy New York street at night, neon lights flicker, a detective in a black trench coat walks briskly. Shot 2 [3–6 seconds] medium shot: The detective enters an old building, rain wets his coat, the door closes slowly behind him. Shot 3 [6–9 seconds] close-up: The detective's focused eyes, distant sirens sound, he frowns slightly. Shot 4 [9–12 seconds] medium shot: The detective moves carefully down a dim hallway, his flashlight illuminating the way. Shot 5 [12–15 seconds] close-up: The detective discovers a key clue, his face shows sudden realization."
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9",
            "prompt_extend": true,
            "watermark": true,
            "duration": 15
        }
    }'

Fornecer um arquivo de áudio

Especifique uma URL de arquivo de áudio personalizada no parâmetro input.audio_url.

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

Dublagem automática

Sem input.audio_url, o modelo gera música de fundo ou efeitos sonoros que correspondem ao conteúdo do vídeo.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.7-t2v-2026-06-12",
        "input": {
            "prompt": "An epic and cute scene. A small, adorable cartoon kitten general, wearing exquisitely detailed golden armor and a slightly oversized helmet, stands bravely on a cliff. He rides a small but heroic warhorse and says: 'The long clouds of Qinghai darken the snowy mountains, a lone city gazes at Yumen Pass from afar. Through a hundred battles in the yellow sand, the golden armor is worn, but we will not return until we have broken Loulan'. Below the cliff, a vast and endless army of mice with makeshift weapons is charging forward. This is a dramatic, large-scale battle scene inspired by ancient Chinese war epics. In the distance, dark clouds gather in the sky over the snowy mountains. The overall atmosphere is a comical and epic fusion of 'cute' and 'domineering'."
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Usar um prompt negativo

Use negative_prompt para excluir o elemento "flor" e impedir que ele apareça no vídeo.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.7-t2v-2026-06-12",
        "input": {
            "prompt": "A kitten running in the moonlight",
            "negative_prompt": "flower"
        },
        "parameters": {
            "resolution": "720P",
            "ratio": "16:9"
        }
    }'

dashscope CLI

Chamada via linha de comando do dashscope.

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

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 string (Obrigatório)

O tipo de conteúdo da requisição. Deve ser application/json.

Authorization string (Obrigatório)

Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx.

X-DashScope-Async string (Obrigatório)

Habilita o processamento assíncrono. Requisições HTTP suportam apenas chamadas assíncronas. Deve ser enable.

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 string (Obrigatório)

Nome do modelo. Para modelos e preços, consulte Preços dos modelos.

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

input object (Obrigatório)

Dados de entrada, incluindo o prompt.

Propriedades

prompt string (Obrigatório)

Prompt de texto descrevendo o conteúdo do vídeo e o estilo visual.

Suporta chinês e inglês. Cada caractere ou letra conta como um. O texto além do limite é truncado automaticamente. Comprimento máximo por modelo:

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

Exemplo: Um gatinho correndo ao luar.

Para dicas, consulte o Guia de prompts de texto para vídeo/imagem para vídeo.

negative_prompt string (Opcional)

Elementos a serem excluídos do vídeo gerado.

Suporta chinês e inglês. Máximo de 500 caracteres; textos mais longos são truncados automaticamente.

Exemplo: baixa resolução, erro, pior qualidade, baixa qualidade, deformado, dedos extras, proporções ruins.

audio_url string (Opcional)

URL do arquivo de áudio para geração de vídeo.

Formatos suportados:

  1. URL pública:

Limites de áudio:

  • Formato: WAV, MP3.
  • Duração: 2–30 segundos.
  • Tamanho do arquivo: Até 15 MB.
  • Tratamento de duração: Se o áudio exceder o valor de duration (por exemplo, 5 segundos), apenas os primeiros 5 segundos serão usados. Se o áudio for mais curto que o vídeo, o restante do vídeo ficará sem som. Por exemplo, um áudio de 3 segundos com um vídeo de 5 segundos produz 3 segundos de áudio seguidos por 2 segundos de silêncio.

parameters object (Opcional)

Parâmetros de geração de vídeo: resolução, reescrita de prompt e marca d'água.

Propriedades

resolution string (Opcional)

ImportanteA resolução afeta o custo. Verifique Preços dos modelos antes de chamar.

Nível de resolução do vídeo gerado. Controla a clareza da saída (contagem total de pixels).

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

ratio string (Opcional)

Proporção de aspecto do vídeo de saída.

  • 16:9 (padrão)
  • 9:16
  • 1:1
  • 4:3
  • 3:4

Resoluções de saída (largura*altura) por proporção de aspecto:

Nível de resolução

Proporção

Resolução do vídeo de saída (largura*altura)

720P

16:9

1280*720

9:16

720*1280

1:1

960*960

4:3

1104*832

3:4

832*1104

1080P

16:9

1920*1080

9:16

1080*1920

1:1

1440*1440

4:3

1648*1248

3:4

1248*1648

duration integer (Opcional)

ImportanteA duração afeta o custo. A cobrança é por segundo. Verifique os preços do modelo antes de fazer a chamada.

Duração do vídeo de saída, em segundos.

  • wan2.7-t2v, wan2.7-t2v-2026-06-12: Um inteiro de 2 a 15. Padrão: 5.

prompt_extendboolean (Opcional)

Ativa a reescrita de prompt. Quando ativado, um LLM reescreve o prompt de entrada para melhorar a qualidade da geração. Ideal para prompts curtos, mas adiciona latência.

  • true (padrão)
  • false

watermark boolean (Opcional)

Adiciona uma marca d'água no canto inferior direito com o texto "AI Generated".

  • false (padrão)
  • true

seed integer (Opcional)

A semente de número aleatório deve ser um inteiro no intervalo [0, 2147483647].

Se não for especificado, uma semente aleatória é gerada. Uma semente fixa melhora a reprodutibilidade.

Como a geração do modelo é probabilística, a mesma semente não garante resultados idênticos.

Parâmetros de resposta

Resposta bem-sucedida

Salve o task_id para consultar o status e o resultado da tarefa.

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

Resposta de erro

Falha na criação da tarefa. Consulte Códigos de erro.

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

output object

Saída da tarefa.

Propriedades

task_id string

O ID da tarefa. Válido para consultas por 24 horas.

task_status string

O status da tarefa.

Valores de enumeração

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: A tarefa não existe ou seu status é desconhecido.

request_id string

Identificador exclusivo da requisição para rastreamento e solução de problemas.

code string

Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro.

message string

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 como UNKNOWN.

Parâmetros de solicitação

Consultar resultado da tarefa

Substitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id é válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu ID do espaço de trabalho real.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Cabeçalhos

Authorization string (Obrigatório)

Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx.

Parâmetros de caminho

task_id string (Obrigatório)

O ID da tarefa.

Parâmetros de resposta

Tarefa executada com sucesso

As URLs de vídeo são válidas por apenas 24 horas e depois são removidas automaticamente. Salve os vídeos gerados prontamente.

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

Falha na execução da tarefa

Quando uma tarefa falha, task_status é FAILED com um código e uma mensagem de erro. Consulte Códigos de erro.

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

Consulta da tarefa expirada

O task_id é válido por 24 horas. Após esse período, as consultas retornam o seguinte erro.

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

outputobject

Saída da tarefa.

Propriedades

task_id string

O ID da tarefa. Válido para consultas por 24 horas.

task_status string

O status da tarefa.

Valores de enumeração

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: A tarefa não existe ou seu status é desconhecido.
Transições de estado durante a consulta:
  • PENDING → RUNNING → SUCCEEDED ou FAILED.
  • O status inicial da consulta geralmente é PENDING ou RUNNING.
  • Quando o status muda para SUCCEEDED, a resposta contém a URL do vídeo gerado.
  • Se o status for FAILED, verifique a mensagem de erro e tente executar a tarefa novamente.

submit_time string

O horário em que a tarefa foi enviada. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

scheduled_time string

O horário em que a tarefa foi executada. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

end_time string

O horário em que a tarefa foi concluída. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

video_url string

URL do vídeo gerado. Retornado apenas quando task_status for SUCCEEDED.

Válido por 24 horas. O vídeo está no formato MP4 com codificação H.264.

orig_prompt string

O prompt de entrada original, correspondente ao parâmetro de requisição prompt.

code string

Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro.

message string

Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro.

usage object

Estatísticas de saída. Retornado apenas para tarefas bem-sucedidas.

Propriedades

duration float

Duração total do vídeo, usada para cobrança.

Igual a output_video_duration.

input_video_duration integer

Valor fixo: 0.

output_video_duration integer

Duração do vídeo de saída em segundos. Corresponde ao valor de input.duration.

SR integer

Nível de resolução do vídeo de saída. Exemplo: 720.

ratio string

Proporção de aspecto do vídeo de saída. Exemplo: 16:9.

video_count integer

Número de vídeos gerados. Sempre 1.

request_id string

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_id retornado para consultar o resultado. O task_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

  • Para criar uma narrativa de múltiplos planos, defina shot_type como "multi".
  • Defina prompt_extend como true para habilitar a reescrita de prompt para otimização do storyboard.
curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.6-t2v",
        "input": {
            "prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \".",
            "audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3"
        },
        "parameters": {
            "size": "1280*720",
            "prompt_extend": true,
            "duration": 10,
            "shot_type":"multi"
        }
    }'

Passar um arquivo de áudio

Modelos suportados: séries wan2.6 e wan2.5.

Defina o parâmetro input.audio_url para uma URL de arquivo de áudio personalizada.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.5-t2v-preview",
        "input": {
            "prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \".",
            "audio_url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3"
        },
        "parameters": {
            "size": "832*480",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Dublagem automática

Modelos suportados: séries wan2.6 e wan2.5.

Sem o parâmetro input.audio_url, o modelo gera música de fundo ou efeitos sonoros que correspondem ao conteúdo do vídeo.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.5-t2v-preview",
        "input": {
            "prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: \"The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them \""
        },
        "parameters": {
            "size": "832*480",
            "prompt_extend": true,
            "duration": 10
        }
    }'

Gerar um vídeo sem som

Apenas 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.

Os modelos das séries wan2.6 e wan2.5 geram vídeos com áudio por padrão.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.2-t2v-plus",
        "input": {
            "prompt": "Low contrast. In a retro 1970s-style subway station, a street musician plays amidst dim colors and rough textures. He wears an old-fashioned jacket and holds a guitar, playing with concentration. Commuters hurry past, and a small crowd gradually gathers to listen. The camera slowly pans to the right, capturing a scene where the sound of the instrument mixes with the city's noise, with old-fashioned subway signs and mottled walls in the background."
        },
        "parameters": {
            "size": "832*480",
            "prompt_extend": true
        }
    }'

Usar um prompt negativo

Modelos suportados: Todos os modelos.

Use negative_prompt para excluir elementos específicos (como "flores") do vídeo gerado.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis' \
        -H 'X-DashScope-Async: enable' \
        -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
        -H 'Content-Type: application/json' \
        -d '{
        "model": "wan2.2-t2v-plus",
        "input": {
            "prompt": "A kitten running in the moonlight",
            "negative_prompt": "flowers"
        },
        "parameters": {
            "size": "832*480"
        }
    }'
Cabeçalhos da requisição

Content-Type string (Obrigatório)

O tipo de conteúdo da requisição. Deve ser application/json.

Authorization string (Obrigatório)

Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx.

X-DashScope-Async string (Obrigatório)

Habilita o processamento assíncrono. Requisições HTTP suportam apenas chamadas assíncronas. Deve ser enable.

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 string (Obrigatório)

Nome do modelo. Para modelos e preços, consulte Preços dos modelos.

Exemplo: wan2.6-t2v.

input object (Obrigatório)

Dados de entrada, incluindo o prompt.

Propriedades

prompt string (Obrigatório)

Prompt de texto descrevendo o conteúdo do vídeo e o estilo visual.

Suporta chinês e inglês. Cada caractere ou letra conta como um. O texto além do limite é truncado automaticamente. Comprimento máximo por modelo:

  • Modelos das séries wan2.6 e wan2.5: Até 1,500 caracteres.
  • Modelos das séries wan2.2 e wan2.1: Até 800 caracteres.

Exemplo: Um gatinho correndo ao luar.

Para dicas, consulte o Guia de Prompts de Texto para Vídeo/Imagem para Vídeo.

negative_prompt string (Opcional)

Elementos a serem excluídos do vídeo gerado.

Suporta chinês e inglês. Máximo de 500 caracteres; textos mais longos são truncados automaticamente.

Exemplo: baixa resolução, erro, pior qualidade, baixa qualidade, desfigurado, dedos extras, proporções ruins.

audio_url string (Opcional)

Modelos suportados: séries wan2.6 e wan2.5.

URL do arquivo de áudio para geração de vídeo.

Formatos suportados:

  1. URL pública:

Limites de áudio:

  • Formato: WAV, MP3.
  • Duração: 3 s a 30 s.
  • Tamanho do arquivo: Até 15 MB.
  • Tratamento de duração: Se o áudio exceder o valor de duration (por exemplo, 5 s), apenas os primeiros 5 s serão usados. Se o áudio for mais curto que o vídeo, o restante do vídeo ficará sem som. Por exemplo, 3 s de áudio com um vídeo de 5 s produz 3 s de áudio seguidos por 2 s de silêncio.

parameters object (Opcional)

Parâmetros de geração de vídeo: resolução, reescrita de prompt e marca d'água.

Propriedades

size string (Opcional)

Importante

  • O parâmetro size afeta o custo: Custo = Preço unitário (baseado na resolução) x Duração (segundos). Para o mesmo modelo: 1080p > 720p > 480p. Verifique os preços do modelo.
  • Defina size para uma resolução específica (como 1280*720), não uma proporção de tela (1:1) ou rótulo de nível (480p).

Resolução do vídeo de saída no formato width*height. Os padrões e valores válidos dependem do modelo:

  • wan2.6-t2v: O valor padrão é 1920*1080 (1080p). Resoluções válidas: todas nos níveis 720p e 1080p.
  • wan2.5-t2v-preview: O valor padrão é 1920*1080 (1080p). Resoluções válidas: todas nos níveis 480p, 720p e 1080p.
  • wan2.2-t2v-plus: O valor padrão é 1920*1080 (1080p). Resoluções válidas: todas nos níveis 480p e 1080p.
  • wan2.1-t2v-turbo: O valor padrão é 1280*720 (720p). Resoluções válidas: todas nos níveis 480p e 720p.
  • wan2.1-t2v-plus: O valor padrão é 1280*720 (720p). Resoluções válidas: todas aquelas no nível 720p.

Resoluções e proporções de aspecto do nível 480p:

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

Resoluções e proporções de aspecto do nível 720p:

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

Resoluções e proporções de aspecto do nível 1080p:

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

duration integer (Opcional)

ImportanteA duração afeta o custo: Custo = Preço unitário (baseado na resolução) x Duração (segundos). Verifique os preços do modelo.

Duração do vídeo de saída em segundos. Os valores válidos dependem do modelo:

  • wan2.6-t2v: Um inteiro de 2 a 15. O valor padrão é 5.
  • wan2.5-t2v-preview: Os valores válidos são 5 e 10. O valor padrão é 5.
  • wan2.2-t2v-plus: Fixo em 5 segundos e não pode ser alterado.
  • wan2.1-t2v-plus: Fixo em 5 segundos e não pode ser alterado.
  • wan2.1-t2v-turbo: Fixo em 5 segundos e não pode ser alterado.

prompt_extendboolean (Opcional)

Ativa a reescrita de prompt. Quando ativado, um LLM reescreve o prompt de entrada para melhorar a qualidade. Ideal para prompts curtos, mas adiciona latência.

  • true (padrão)
  • false

shot_type string (Opcional)

Modelos suportados: modelos wan2.6.

Estrutura de planos para o vídeo de saída: um plano contínuo ou múltiplos planos com transições.

Valores válidos:

  • single (padrão)
  • multi

Este parâmetro só tem efeito quando "prompt_extend": true está definido.

Prioridade: shot_type substitui o prompt. Definir shot_type como single produz um vídeo de plano único mesmo que o prompt solicite múltiplos planos.

watermark boolean (Opcional)

Adiciona uma marca d'água no canto inferior direito com o texto "AI Generated".

  • false (padrão)
  • true

seed integer (Opcional)

A semente de número aleatório deve ser um inteiro no intervalo [0, 2147483647].

Se não for especificado, uma semente aleatória é gerada. Uma semente fixa melhora a reprodutibilidade.

Como a geração do modelo é probabilística, a mesma semente não garante resultados idênticos.

Parâmetros de resposta

Resposta bem-sucedida

Salve o task_id para consultar o status e o resultado da tarefa.

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

Resposta de erro

Falha na criação da tarefa. Consulte Códigos de erro.

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

output object

Saída da tarefa.

Propriedades

task_id string

O ID da tarefa. Válido para consultas por 24 horas.

task_status string

O status da tarefa.

Valores de enumeração

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: A tarefa não existe ou seu status é desconhecido.

request_id string

Identificador exclusivo da requisição para rastreamento e solução de problemas.

code string

Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro.

message string

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 como UNKNOWN.

Parâmetros de solicitação

Consultar resultado da tarefa

Substitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id é válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu ID do espaço de trabalho real.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Cabeçalhos

Authorization string (Obrigatório)

Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx.

Parâmetros de caminho

task_id string (Obrigatório)

O ID da tarefa.

Parâmetros de resposta

Tarefa executada com sucesso

As URLs de vídeo são válidas por apenas 24 horas e depois são removidas automaticamente. Salve os vídeos gerados prontamente.

{
        "request_id": "abbf7aa3-9652-4785-a622-xxxxxx",
        "output": {
            "task_id": "38513c71-5190-48e1-9f3b-xxxxxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2025-09-29 14:05:22.119",
            "scheduled_time": "2025-09-29 14:05:28.278",
            "end_time": "2025-09-29 14:10:00.437",
            "orig_prompt": "Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective's office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them'.",
            "video_url": "https://dashscope-result-sh.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx"
        },
        "usage": {
            "duration": 10,
            "size": "1280*720",
            "input_video_duration": 0,
            "output_video_duration": 10,
            "video_count": 1,
            "SR": 720
        }
    }

Falha na execução da tarefa

Quando uma tarefa falha, task_status é FAILED com um código e uma mensagem de erro. Consulte Códigos de erro.

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

Consulta da tarefa expirada

O task_id é válido por 24 horas. Após esse período, as consultas retornam o seguinte erro.

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

outputobject

Saída da tarefa.

Propriedades

task_id string

O ID da tarefa. Válido para consultas por 24 horas.

task_status string

O status da tarefa.

Valores de enumeração

  • PENDING
  • RUNNING
  • SUCCEEDED
  • FAILED
  • CANCELED
  • UNKNOWN: A tarefa não existe ou seu status é desconhecido.
Transições de estado durante a consulta:
  • PENDING → RUNNING → SUCCEEDED ou FAILED.
  • O status inicial da consulta geralmente é PENDING ou RUNNING.
  • Quando o status muda para SUCCEEDED, a resposta contém a URL do vídeo gerado.
  • Se o status for FAILED, verifique a mensagem de erro e tente executar a tarefa novamente.

submit_time string

O horário em que a tarefa foi enviada. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

scheduled_time string

O horário em que a tarefa foi executada. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

end_time string

O horário em que a tarefa foi concluída. O horário está em UTC+8 e o formato é AAAA-MM-DD HH:mm:ss.SSS.

video_url string

URL do vídeo gerado. Retornado apenas quando task_status for SUCCEEDED.

Válido por 24 horas. O vídeo está no formato MP4 com codificação H.264.

orig_prompt string

O prompt de entrada original, correspondente ao parâmetro de requisição prompt.

actual_prompt string

Quando prompt_extend=true, o sistema reescreve o prompt de entrada. Este campo contém o prompt reescrito usado para a geração.

  • Não retornado quando prompt_extend=false.
  • O modelo wan2.6 não retorna este campo, independentemente do valor de prompt_extend.

code string

Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro.

message string

Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro.

usage object

Estatísticas de saída. Retornado apenas para tarefas bem-sucedidas.

Propriedades

video_duration integer

Retornado apenas para wan2.5 e anteriores (usado para cobrança).

Duração do vídeo de saída em segundos. Valores válidos: 5, 10.

duration float

Retornado apenas para wan2.6 (usado para cobrança).

Duração total do vídeo. Fórmula: duration=input_video_duration+output_video_duration.

input_video_duration integer

Retornado apenas para wan2.6. Valor fixo: 0.

output_video_duration integer

Retornado apenas para wan2.6.

Duração do vídeo de saída em segundos. Corresponde ao valor de input.duration.

SR integer

Retornado apenas para wan2.6. Nível de resolução do vídeo de saída. Exemplo: 720.

size string

Retornado apenas para wan2.6. Resolução de saída no formato "largura×altura". Exemplo: 1920×1080.

video_ratio string

Retornado apenas para wan2.5 e anteriores. Resolução de saída no formato "largura×altura". Exemplo: 832×480.

video_count integer

Número de vídeos gerados. Sempre 1.

request_id string

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
  1. 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
}
  1. 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
  1. 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"
	}
}
  1. 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 de resolution (nível de resolução) e ratio (proporção de tela) para definir a resolução de saída. Modelos anteriores usavam o campo size.
  • Remoção do tipo de plano: wan2.7 remove o campo shot_type. Em vez disso, descreva a estrutura de planos diretamente no prompt.

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)

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.