Os modelos de texto para vídeo Wan geram vídeos a partir de entradas de texto, imagens e áudio. O wan3.0-video suporta até 30 segundos, proporção adaptável, duração inteligente, resoluções 480P/720P/1080P, alternância de áudio, áudio de referência, além de arquivos e links da web de referência.
Vídeo de saída (múltiplas tomadas, com áudio ativado)
Tomada 1 A sequência começa com um plano geral extremo. A câmera inicia em um ângulo baixo, próximo ao solo, e avança pela pradaria enquanto se inclina para cima. À medida que a câmera sobe do nível do chão para uma posição levemente elevada, a chita entra no quadro pela esquerda. Essa tomada estabelece uma relação espacial clara ao colocar a chita e o antílope em fuga no mesmo caminho. Tomada 2 A câmera desce para um nível próximo ao solo e se move para a direita, paralela à chita. A chita é mantida consistentemente à esquerda do centro, o que cria um deslocamento lateral contínuo no fundo. Por um período, o movimento da câmera permanece estável para aumentar a sensação de velocidade e continuidade espacial. Tomada 3 Ainda se movendo para a direita, a câmera executa um leve arco ao longo da parte interna do trajeto da chita. Esse movimento cria um efeito sutil de órbita no quadro enquanto a câmera continua a seguir o assunto. Tomada 4 A câmera desacelera gradualmente seu movimento lateral e fica relativamente estável enquanto aplica zoom simultaneamente. Essa ação estreita o foco para a distância cada vez menor entre a chita e o antílope. Tomada 5 A câmera volta a avançar e desce ligeiramente, rente ao solo, para reduzir a distância entre os dois animais. A tomada para no ponto crítico, exatamente quando as patas dianteiras da chita estão prestes a alcançar a traseira do antílope, criando intensa pressão e tensão. Essa ação é sincronizada com uma trilha sinfônica em crescendo, batidas de tambor cada vez mais densas e sons de vento e passos que impulsionam o ritmo. No momento final, o volume da música cai, deixando apenas sons ambientes e rítmicos para criar uma breve pausa.
Antes de fazer uma chamada de API, get an API key e set it as an environment variable. Para usar um SDK, install the DashScope SDK. Todos os exemplos usam chamadas assíncronas que enviam uma tarefa de geração de vídeo e consultam o resultado periodicamente.
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior antes de executar o código a seguir.Se a versão for muito antiga, erros como "url error, please check url!" podem ocorrer. Para atualizar o SDK, consulte Install the SDK.
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# The API key varies by region. For more information about how to obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-keyapi_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")print('please wait...')rsp = VideoSynthesis.call(api_key=api_key, model='wan3.0-video', prompt='Shot 1: Opening with a long shot. The camera starts from a low angle close to the ground and moves forward across the grassland. At the same time, the camera moves upward, gradually raising the point of view from ground level to a slightly elevated position. A cheetah enters the frame from the left, on the same chase path as a fleeing antelope in front of it, establishing a clear foreground-background spatial relationship. Shot 2: The camera moves downward, returning to a position close to the ground, and pans right to follow the cheetah\'s movement, steadily tracking it from a parallel side view. The subject remains consistently positioned slightly to the left of the frame\'s center, creating a continuous lateral movement effect in the background. The camera movement stays stable for a while to enhance the sense of speed and spatial continuity. Shot 3: While maintaining the rightward movement, the camera moves in a slight arc along the inside of the cheetah\'s path. This creates a subtle circling effect in the shot, but the camera always moves in the same direction as the subject. Shot 4: Gradually slow down the lateral movement and transition to a relatively stable camera position. At the same time, execute a zoom-in, progressively narrowing the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward again and slightly downward, closing in on the space between the two animals near the ground. It holds the shot at the critical moment when the cheetah\'s forelimbs are about to reach the antelope\'s rear, creating intense pressure and tension. This is accompanied by a crescendoing symphonic score, an increasingly intense drumbeat, and the sounds of wind and footsteps to drive the rhythm. In the final moments, the music volume drops, leaving only ambient and rhythmic sounds for a brief pause.', resolution="720P", ratio="16:9", duration=15, watermark=True)print(rsp)if rsp.status_code == HTTPStatus.OK: print("video_url:", rsp.output.video_url)else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior antes de executar o código a seguir.Se a versão for muito antiga, erros como "url error, please check url!" podem ocorrer. Para atualizar o SDK, consulte Install the SDK.
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx" // API keys vary by region. To obtain an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan3.0-video") .prompt("Shot 1: Open with a long shot. The camera starts at a low angle near the ground, dollying forward across the grassland while simultaneously craning up. The perspective lifts from ground level to a slightly elevated position, allowing a cheetah to enter the frame from the left, on the same chase path as a fleeing antelope ahead, establishing a clear spatial depth. Shot 2: The camera moves down to near ground level and tracks right, following the cheetah's movement. It maintains a stable, parallel tracking shot. The subject remains just left of the frame's center, creating a continuous lateral movement in the background. The camera motion stays steady for a period to enhance the sense of speed and spatial continuity. Shot 3: While maintaining the rightward track, the camera executes a slight arc along the inner side of the cheetah's path. This creates a subtle orbiting effect in the shot, while the camera continues to point in the same direction as the subject. Shot 4: Gradually slow the lateral movement, transitioning to a relatively stable camera position. Simultaneously, execute a zoom-in, progressively narrowing the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward and slightly downward again, staying close to the ground to close in on the space between the two. It stops at the critical moment just as the cheetah's forelimbs are about to reach the antelope's rear, creating intense pressure and tension. This is accompanied by a gradually intensifying orchestral score, increasingly dense drumbeats, and the sounds of wind and footsteps to drive the rhythm. In the final stage, the music volume is lowered, leaving only ambient and rhythmic sounds for a brief pause.") .duration(15) .resolution("720P") .ratio("16:9") .watermark(true) .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); }}
Etapa 1: Crie uma tarefa para obter o ID da tarefa
Copy
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": "wan3.0-video", "input": { "prompt": "Shot 1: An extreme long shot opens the scene. The camera starts from a low angle near the ground and moves forward across the grassland. It simultaneously tilts up, raising the perspective from ground level to a slightly higher position. This brings a cheetah into the frame from the left, placing it on the same chase path as a fleeing antelope ahead and establishing a clear spatial relationship. Shot 2: The camera moves down, returning to near ground level, and tracks right along the cheetahs path of motion. It maintains a stable, parallel side-on follow shot, keeping the subject in the left-center of the frame as the background scrolls horizontally. The camera movement remains steady for a period to enhance the sense of speed and spatial continuity. Shot 3: While continuing to track right, the camera makes a slight arc along the inner side of the cheetahs path, creating a subtle orbiting effect while always moving in the same direction as the subject. Shot 4: The camera gradually slows its horizontal movement and transitions to a relatively stable position while zooming in. This progressively compresses the visual focus onto the shrinking distance between the cheetah and the antelope. Shot 5: The camera moves forward again and slightly down, closing in on the space between them near the ground. It stops at the critical moment when the cheetahs forelimbs are about to reach the antelopes rear, creating intense pressure and tension. This is accompanied by a crescendo of symphonic music, an accelerating drumbeat, and the sounds of wind and paws hitting the ground to drive the rhythm. In the final stage, the music fades, leaving only ambient sounds and the rhythmic beat for a brief pause." }, "parameters": { "resolution": "720P", "ratio": "16:9", "watermark": true, "duration": 15 }}'
Etapa 2: Recupere o resultado usando o ID da tarefaSubstitua {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 workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de exemplo: modelos wan2.6 e anteriores
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior antes de executar o código a seguir.Se a versão for muito antiga, erros como "url error, please check url!" podem ocorrer. Para atualizar o SDK, consulte Install the SDK.
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key.api_key = os.getenv("DASHSCOPE_API_KEY", "YOUR_API_KEY")print('please wait...')rsp = VideoSynthesis.call(api_key=api_key, model='wan2.6-t2v', prompt='A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization.', size="1280*720", duration=15, shot_type="multi", watermark=True)print(rsp)if rsp.status_code == HTTPStatus.OK: print("video_url:", rsp.output.video_url)else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior antes de executar o código a seguir.Se a versão for muito antiga, erros como "url error, please check url!" podem ocorrer. Para atualizar o SDK, consulte Install the SDK.
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key. // The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key. static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan2.6-t2v") .prompt("A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization.") .duration(15) .size("1280*720") .shotType("multi") .watermark(true) .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); }}
Etapa 1: Crie uma tarefa para obter o ID da tarefa
Copy
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": "A thrilling detective chase story with cinematic storytelling. Shot 1 [0-3s]: Wide shot of a rainy New York street at night, neon lights flickering, a detective in a black trench coat walking briskly. Shot 2 [3-6s]: Medium shot of the detective entering an old building, rain soaking his coat, the door closing slowly behind him. Shot 3 [6-9s]: Close-up of the detectives focused, determined eyes as distant sirens wail and he frowns slightly in thought. Shot 4 [9-12s]: Medium shot of the detective moving carefully down a dim hallway, his flashlight illuminating the path ahead. Shot 5 [12-15s]: Close-up of the detective discovering a key clue, his face lighting up with sudden realization." }, "parameters": { "size": "1280*720", "watermark": true, "duration": 15, "shot_type":"multi" }}'
Etapa 2: Recupere o resultado usando o ID da tarefaSubstitua {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 workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Saída de exemplo
O video_url é válido por 24 horas. Baixe o vídeo prontamente.
Os modelos suportados variam conforme a região. Os recursos são isolados entre as regiões. Ao fazer uma chamada, certifique-se de que o modelo, a URL do endpoint e a chave da API pertençam à mesma região. Chamadas entre regiões falham.Modelos suportados:
Global
International
US
Chinese mainland
Se você selecionar o escopo de implantação Global, os recursos computacionais de inferência do modelo são agendados dinamicamente em escala global. Os dados estáticos são armazenados na região selecionada. Regiões suportadas: US (Virginia), Germany (Frankfurt),China (Hong Kong).
Model
Features
Input modality
Output video specifications
wan2.6-t2v Recommended
Vídeo com áudio
Narrativa multi-cena, sincronização de áudio e vídeo
Se você selecionar o escopo de implantação International, os recursos computacionais de inferência do modelo são agendados dinamicamente em escala global, excluindo a China continental. Os dados estáticos são armazenados na região selecionada. Região suportada: Singapore.
Model
Features
Input modality
Output video specifications
wan2.7-t2v-2026-04-25 Recommended
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.7-t2v
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.6-t2v
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.5-t2v-preview
Vídeo com áudioSincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 480P, 720P, 1080PDuração do vídeo: 5s, 10sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wan2.2-t2v-plus
Vídeo sem áudio
Maior estabilidade e taxa de sucesso em comparação ao modelo 2,1.
Texto
Opções de resolução: 480P, 1080PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wan2.1-t2v-turbo
Vídeo sem áudio
Texto
Opções de resolução: 480P, 720PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wan2.1-t2v-plus
Vídeo sem áudio
Texto
Opções de resolução: 720PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
Se você selecionar o escopo de implantação US, os recursos computacionais de inferência do modelo ficam restritos aos Estados Unidos. Os dados estáticos são armazenados na região selecionada. Região suportada: US (Virginia).
Model
Features
Input modality
Output video specifications
wan2.6-t2v-us Recommended
Vídeo com áudio
Narrativa multi-cena, sincronização de áudio e vídeo
Se você selecionar o escopo de implantação Chinese mainland, os recursos computacionais de inferência do modelo ficam restritos à China continental. Os dados estáticos são armazenados na região selecionada. Região suportada: China (Beijing).
Model
Features
Input modality
Output video specifications
wan2.7-t2v-2026-04-25 Recommended
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.7-t2v
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.6-t2v
Vídeo com áudioNarrativa multi-cena, sincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 720P, 1080PDuração do vídeo: [2s, 15s] (inteiro)Especificações definidas: 30 fps, MP4 (codificação H.264)
wan2.5-t2v-preview
Vídeo com áudioSincronização de áudio e vídeo
Texto, áudio
Opções de resolução: 480P, 720P, 1080PDuração do vídeo: 5s, 10sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wan2.2-t2v-plus
Vídeo sem áudio
Maior estabilidade e taxa de sucesso em comparação ao modelo 2,1.
Texto
Opções de resolução: 480P, 1080PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wanx2.1-t2v-turbo
Vídeo sem áudio
Texto
Opções de resolução: 480P, 720PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
wanx2.1-t2v-plus
Vídeo sem áudio
Texto
Opções de resolução: 720PDuração do vídeo: 5sEspecificações definidas: 30 fps, MP4 (codificação H.264)
O código de exemplo neste tópico aplica-se à região Singapore.
Modelos suportados: wan3.0, wan2.7, and wan2.6 series.Descrição: Alterna automaticamente entre as tomadas — por exemplo, de um plano geral para um close-up. Ideal para videoclipes e narrativas cinematográficas.Parâmetros:
wan2.7: O parâmetro shot_type não é obrigatório. Descreva a estrutura das tomadas no prompt usando linguagem natural, como timestamps para definir as cenas. Caso o prompt não contenha descrições da estrutura de tomadas, o modelo analisa a semântica e determina automaticamente se deve gerar um vídeo com tomada única ou múltiplas tomadas.
wan2.6: Defina o parâmetro shot_type como "multi" e configure o parâmetro prompt_extend como true para ativar a reescrita inteligente e otimizar as descrições das tomadas.
Prompt de entrada
Vídeo de saída (wan3.0)
Uma visão de harmonia entre tecnologia futura e natureza. Tomada 1 [0-2s]: Plano geral de um jardim aéreo em uma cidade futurista, com plantas flutuantes balançando suavemente ao vento. Tomada 2 [2-4s]: Um robô jardineiro poda cuidadosamente as plantas com movimentos precisos e graciosos. Tomada 3 [4-7s]: A luz do sol atravessa uma cúpula transparente, iluminando todo o jardim e exibindo a fusão perfeita entre tecnologia e natureza. Tomada 4 [7-10s]: A câmera se afasta para revelar a grande escala de toda a cidade futurista, com o jardim aéreo sendo apenas uma parte dela.
Este é um clipe de filme de artes marciais centrado em um duelo intenso. Em uma clareira de pedras sob o sol do meio-dia, dois homens avançam um contra o outro. Um ataca com a palma da mão, mas seu oponente gira e bloqueia com o braço, e o impacto levanta poeira do chão. Eles então trocam socos rápidos e golpes de palma em um espaço restrito. Um deles salta no ar para uma série de chutes pesados, forçando o oponente a cruzar os braços para bloquear e deslizar vários metros para trás, deixando marcas brancas nítidas na superfície de pedra. Por fim, eles se afastam, respirando pesadamente e trocando olhares fixos. A cena apresenta uma textura de ação realista com iluminação marcante, criando um tom que varia de uma explosão poderosa a um confronto tenso.
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key.api_key = os.getenv("DASHSCOPE_API_KEY")def sample_async_call_t2v(): # Asynchronous invocation that returns a task_id. rsp = VideoSynthesis.async_call(api_key=api_key, model='wan3.0-video', prompt='A vision of harmony between future technology and nature. Shot 1 [0-2s]: Wide shot of an aerial garden in a futuristic city, floating plants swaying gently in the breeze. Shot 2 [2-4s]: A robot gardener carefully trims plants with precise, graceful movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the grand scale of the entire futuristic city, with the aerial garden as just one part of it.', resolution='720P', ratio='16:9', duration=10, watermark=True, seed=12345) print(rsp) if rsp.status_code == HTTPStatus.OK: print("task_id: %s" % rsp.output.task_id) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message)) # Wait for the asynchronous task to complete. rsp = VideoSynthesis.wait(task=rsp, api_key=api_key) print(rsp) if rsp.status_code == HTTPStatus.OK: print(rsp.output.video_url) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))if __name__ == '__main__': sample_async_call_t2v()
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key. // The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key. static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan3.0-video") .prompt("A vision of harmony between future technology and nature. Shot 1 [0-2s]: Wide shot of an aerial garden in a futuristic city, floating plants swaying gently in the breeze. Shot 2 [2-4s]: A robot gardener carefully trims plants with precise, graceful movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the grand scale of the entire futuristic city, with the aerial garden as just one part of it.") .resolution("720P") .ratio("16:9") .duration(10) .watermark(true) .seed(12345) .build(); // Asynchronous invocation VideoSynthesisResult task = vs.asyncCall(param); System.out.println(JsonUtils.toJson(task)); System.out.println("please wait..."); // Get the result VideoSynthesisResult result = vs.wait(task, apiKey); 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); }}
Etapa 1: Crie uma tarefa para obter o ID da tarefa
Copy
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": "wan3.0-video", "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": { "resolution": "720P", "ratio": "16:9", "duration": 10 }}'
Etapa 2: Recupere o resultado usando o ID da tarefaSubstitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id permanece válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de exemplo: wan2.6
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"# API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-keyapi_key = os.getenv("DASHSCOPE_API_KEY")def sample_async_call_t2v(): # Make an asynchronous invocation to return a task_id. rsp = VideoSynthesis.async_call(api_key=api_key, model='wan2.6-t2v', prompt='Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part.', size='1280*720', duration=10, shot_type='multi', watermark=True, seed=12345) print(rsp) if rsp.status_code == HTTPStatus.OK: print("task_id: %s" % rsp.output.task_id) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message)) # Wait for the asynchronous task to complete. rsp = VideoSynthesis.wait(task=rsp, api_key=api_key) print(rsp) if rsp.status_code == HTTPStatus.OK: print(rsp.output.video_url) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))if __name__ == '__main__': sample_async_call_t2v()
Certifique-se de que seu DashScope Java SDK esteja na versão 2.22.14 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx" // API keys vary by region. To obtain an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan2.6-t2v") .prompt("Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part.") .negativePrompt("") .size("1280*720") .duration(10) .shotType("multi") .watermark(true) .seed(12345) .build(); // Asynchronous invocation VideoSynthesisResult task = vs.asyncCall(param); System.out.println(JsonUtils.toJson(task)); System.out.println("please wait..."); // Get the result VideoSynthesisResult result = vs.wait(task, apiKey); 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); }}
Etapa 1: Crie uma tarefa para obter o ID da tarefa
Copy
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": "Show a beautiful vision of the future where technology and nature coexist in harmony. Shot 1 [0-2s]: A panoramic view of a hanging garden in a futuristic city, with floating plants swaying in the breeze. Shot 2 [2-4s]: A robot gardener meticulously prunes the plants with precise and elegant movements. Shot 3 [4-7s]: Sunlight streams through a transparent dome, illuminating the entire garden and showcasing the perfect fusion of technology and nature. Shot 4 [7-10s]: The camera pulls back to reveal the magnificent view of the entire futuristic city, of which the hanging garden is just one part." }, "parameters": { "size": "1280*720", "watermark": true, "duration": 10, "shot_type": "multi" }}'
Etapa 2: Recupere o resultado usando o ID da tarefaSubstitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id permanece válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Modelos suportados: wan3.0, wan2.7, wan2.6, and wan2.5 series.Descrição: Os personagens do vídeo podem "falar" ou cantar, com movimentos labiais sincronizados ao áudio. Para mais exemplos, consulte Video audio generation.Parâmetros:
Fornecer um arquivo de áudio: Defina audio_url. O modelo sincroniza os movimentos labiais com o arquivo de áudio.
Dublagem automática: Na ausência de audio_url, o modelo gera automaticamente um vídeo com áudio por padrão, adicionando efeitos sonoros de fundo, música ou vozes com base no conteúdo visual.
Exemplo de entrada
Vídeo de saída (vídeo com áudio)
Prompt de entrada: Cena filmada em ângulo baixo, plano médio fechado, tons quentes e iluminação mista (a luz prática do abajur se mistura à luz nublada da janela), com iluminação lateral e composição centralizada. Em um escritório clássico de detetive, estantes de madeira repletas de arquivos antigos e cinzeiros. Um abajur verde ilumina um dossiê aberto no centro da mesa. Uma raposa, vestindo um sobretudo marrom-escuro e um chapéu fedora cinza-claro, senta-se em uma cadeira de couro; sua pelagem é carmesim, a cauda repousa levemente na borda e seus dedos viram lentamente páginas amareladas. Lá fora, uma garoa constante cai sob um céu azul, marcando o vidro com rastros sinuosos. Ela levanta a cabeça devagar, as orelhas tremem ligeiramente e seus olhos âmbar fitam diretamente a câmera, enquanto sua boca se move claramente ao falar com uma voz suave e cínica: 'O caso estava frio, mais frio que um peixe no inverno. Mas toda galinha tem seus segredos, e eu, particularmente, pretendia encontrá-los'.Áudio de entrada:
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key.api_key = os.getenv("DASHSCOPE_API_KEY")def sample_async_call_t2v(): # Asynchronous invocation that returns a task_id. rsp = VideoSynthesis.async_call(api_key=api_key, model='wan3.0-video', 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', resolution='720P', ratio='16:9', duration=10, watermark=True, seed=12345) print(rsp) if rsp.status_code == HTTPStatus.OK: print("task_id: %s" % rsp.output.task_id) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message)) # Wait for the asynchronous task to complete. rsp = VideoSynthesis.wait(task=rsp, api_key=api_key) print(rsp) if rsp.status_code == HTTPStatus.OK: print(rsp.output.video_url) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))if __name__ == '__main__': sample_async_call_t2v()
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key. // The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key. static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan3.0-video") .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") .resolution("720P") .ratio("16:9") .duration(10) .watermark(true) .seed(12345) .build(); // Asynchronous invocation VideoSynthesisResult task = vs.asyncCall(param); System.out.println(JsonUtils.toJson(task)); System.out.println("please wait..."); // Get the result VideoSynthesisResult result = vs.wait(task, apiKey); 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); }}
Etapa 1: Criar uma tarefa para obter o ID da tarefa
Copy
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": "wan3.0-video", "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": { "resolution": "720P", "ratio": "16:9", "watermark": true, "duration": 10 }}'
Etapa 2: Recuperar o resultado usando o ID da tarefaSubstitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id permanece válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Código de exemplo: wan2.6
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# If you have not configured the environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx"# API keys vary by region. To get an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-keyapi_key = os.getenv("DASHSCOPE_API_KEY")def sample_async_call_t2v(): # Make an asynchronous invocation to return a task_id. rsp = VideoSynthesis.async_call(api_key=api_key, model='wan2.6-t2v', prompt="Shot from a low angle, in a medium close-up, with warm tones, mixed lighting (the practical light from the desk lamp blends with the overcast light from the window), side lighting, and a central composition. In a classic detective office, wooden bookshelves are filled with old case files and ashtrays. A green desk lamp illuminates a case file spread out in the center of the desk. A fox, wearing a dark brown trench coat and a light gray fedora, sits in a leather chair, its fur crimson, its tail resting lightly on the edge, its fingers slowly turning yellowed pages. Outside, a steady drizzle falls beneath a blue sky, streaking the glass with meandering streaks. It slowly raises its head, its ears twitching slightly, its amber eyes gazing directly at the camera, its mouth clearly moving as it speaks in a smooth, cynical voice: 'The case was cold, colder than a fish in winter. But every chicken has its secrets, and I, for one, intended to find them '.", audio_url='https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250929/stjqnq/%E7%8B%90%E7%8B%B8.mp3', size='1280*720', duration=10, watermark=True, seed=12345) print(rsp) if rsp.status_code == HTTPStatus.OK: print("task_id: %s" % rsp.output.task_id) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message)) # Wait for the asynchronous task to complete. rsp = VideoSynthesis.wait(task=rsp, api_key=api_key) print(rsp) if rsp.status_code == HTTPStatus.OK: print(rsp.output.video_url) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))if __name__ == '__main__': sample_async_call_t2v()
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured the environment variable, replace the following line with your Model Studio API key: apiKey="sk-xxx" // API keys vary by region. To get an API key, visit: https://www.alibabacloud.com/help/en/model-studio/get-api-key static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); 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) .watermark(true) .seed(12345) .build(); // Make an asynchronous invocation. VideoSynthesisResult task = vs.asyncCall(param); System.out.println(JsonUtils.toJson(task)); System.out.println("please wait..."); // Get the result. VideoSynthesisResult result = vs.wait(task, apiKey); 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); }}
Etapa 1: Criar uma tarefa para obter o ID da tarefa
Copy
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", "duration": 10 }}'
Etapa 2: Recuperar o resultado usando o ID da tarefaSubstitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id permanece válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Modelos suportados: wan2.2 series, wan2.1 series.Descrição: Ideal para cenários que exigem apenas conteúdo visual, como pôsteres dinâmicos e curtas-metragens sem som.Parâmetros: Os modelos wan2.2 e anteriores geram vídeos sem áudio por padrão. Nenhuma configuração adicional é necessária.
Prompt de entrada
Vídeo de saída (vídeo sem áudio)
Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene.
Python SDK
Java SDK
curl
Certifique-se de que seu DashScope SDK for Python esteja na versão 1.25.16 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
import osfrom http import HTTPStatusfrom dashscope import VideoSynthesisimport dashscope# The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-referencedashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'# If you have not configured environment variables, replace the following line with api_key="sk-xxx". Use your Model Studio API key.# The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key.api_key = os.getenv("DASHSCOPE_API_KEY")def sample_async_call_t2v(): # Asynchronous invocation that returns a task_id. rsp = VideoSynthesis.async_call(api_key=api_key, model='wan2.2-t2v-plus', prompt='Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene.', size='832*480', watermark=True, seed=12345) print(rsp) if rsp.status_code == HTTPStatus.OK: print("task_id: %s" % rsp.output.task_id) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message)) # Wait for the asynchronous task to complete. rsp = VideoSynthesis.wait(task=rsp, api_key=api_key) print(rsp) if rsp.status_code == HTTPStatus.OK: print(rsp.output.video_url) else: print('Failed, status_code: %s, code: %s, message: %s' % (rsp.status_code, rsp.code, rsp.message))if __name__ == '__main__': sample_async_call_t2v()
Certifique-se de que seu DashScope SDK for Java esteja na versão 2.22.14 ou posterior. Para atualizar o SDK, consulte Install the SDK .
Copy
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;public class Text2Video { static { // The following URL is for the Singapore region. URLs differ by region. To obtain the URL for your region, visit: https://www.alibabacloud.com/help/en/model-studio/text-to-video-api-reference Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"; } // If you have not configured environment variables, replace the following line with apiKey="sk-xxx". Use your Model Studio API key. // The API key varies by region. For more information about how to get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key. static String apiKey = System.getenv("DASHSCOPE_API_KEY"); public static void text2video() throws ApiException, NoApiKeyException, InputRequiredException { VideoSynthesis vs = new VideoSynthesis(); VideoSynthesisParam param = VideoSynthesisParam.builder() .apiKey(apiKey) .model("wan2.2-t2v-plus") .prompt("Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene.") .size("832*480") .watermark(true) .seed(12345) .build(); // Asynchronous invocation VideoSynthesisResult task = vs.asyncCall(param); System.out.println(JsonUtils.toJson(task)); System.out.println("please wait..."); // Get the result VideoSynthesisResult result = vs.wait(task, apiKey); 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); }}
Etapa 1: Criar uma tarefa para obter o ID da tarefa
Copy
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": "Rim light, low contrast, medium close-up, daylight, left-heavy composition, clean single-person shot, warm tones, soft light, sunny day light, side light, daytime. A young girl sits in a field of tall grass with two fluffy donkeys standing behind her. The girl, about eleven or twelve, wears a simple floral dress, her hair in two braids, and has an innocent smile. She sits cross-legged, gently touching the wildflowers beside her. The donkeys are sturdy, their ears pricked up, curiously looking toward the camera. Sunlight bathes the field, creating a warm and natural scene." }, "parameters": { "size": "832*480", "watermark": true }}'
Etapa 2: Recuperar o resultado usando o ID da tarefaSubstitua {task_id} pelo valor de task_id retornado pela chamada de API anterior. O task_id permanece válido para consultas por 24 horas. Substitua {WorkspaceId} pelo seu workspace ID real.
Copy
curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \--header "Authorization: Bearer $DASHSCOPE_API_KEY"
P: Quais alterações de código são necessárias para atualizar do wan2.7 para o wan3.0?
Nome do modelo: Altere o model de wan2.7-t2v-* para wan3.0-video.
Remover prompt_extend: O wan3.0 não oferece suporte ao parâmetro prompt_extend. Remova este campo.
Duração estendida: O wan3.0 suporta até 30 segundos (o wan2.7 suporta até 15 segundos). Defina duration como um número inteiro entre 2 e 30.
Nova entrada de arquivo e web: O wan3.0 permite passar type: "file" (docx, ppt, pdf, etc.) ou type: "link" (URL pública da web) em input.media. O modelo compreende automaticamente o conteúdo e gera um vídeo. Não é possível usar esses dois tipos simultaneamente.
P: Os vídeos gerados no console possuem marca d'água. Como removê-la?
A página de geração de vídeo no console do Model Studio não disponibiliza uma opção para marca d'água, portanto, não é possível desativá-la pelo console.
Ao chamar o modelo via API, defina watermark como false para gerar um vídeo sem marca d'água.
Se você omitir o parâmetro watermark, a API adicionará uma marca d'água por padrão. O código de exemplo neste tópico passa watermark=true; altere para false para remover a marca d'água.
P: Comprei um plano de economia de uso geral de IA. Por que os vídeos gerados ainda têm marca d'água?
Um plano de economia de uso geral de IA apenas compensa seus custos. Ele não altera a saída do modelo e não tem relação com a presença de marca d'água no vídeo.
A marca d'água é controlada exclusivamente pelo parâmetro watermark da API: defina-o como false para remover a marca d'água ou omita-o para manter a marca d'água padrão.