Model pengeditan video Wan 2.7 menerima input multimodal (teks, gambar, dan video) untuk pengeditan berbasis instruksi dan style transfer .
Dokumen terkait: Panduan
Penerapan
Model, URL titik akhir, dan Kunci API harus berada di Wilayah yang sama. Panggilan lintas-wilayah akan gagal.
- Pilih model: Konfirmasi wilayah model tersebut.
- Pilih URL titik akhir: Gunakan URL titik akhir yang sesuai dengan wilayah Anda. Didukung melalui HTTP dan SDK DashScope.
- Konfigurasikan Kunci API: Dapatkan Kunci API untuk wilayah tersebut, lalu konfigurasikan sebagai variabel lingkungan.
CatatanKode contoh dalam topik ini menggunakan Singapura.
PentingAlibaba Cloud Model Studio telah merilis domain khusus ruang kerja untuk wilayah China (Beijing) dan Singapura. Domain khusus baru ini memberikan performa lebih unggul dan stabilitas lebih tinggi untuk permintaan inferensi. Kami merekomendasikan migrasi ke domain baru:
- China (Beijing): dari
https://dashscope.aliyuncs.comkehttps://{WorkspaceId}.cn-beijing.maas.aliyuncs.com - Singapura: dari
https://dashscope-intl.aliyuncs.comkehttps://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com
{WorkspaceId} adalah ID ruang kerja Anda, yang dapat ditemukan pada halaman Detail Ruang Kerja di Konsol Alibaba Cloud Model Studio. Domain lama tetap berfungsi penuh.
HTTP
Tugas pengeditan video biasanya memerlukan waktu 1 hingga 5 menit. API menggunakan panggilan asinkron dengan dua langkah utama: Buat tugas → Polling hasilnya.
Langkah 1: Buat tugas
Singapura
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Beijing
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis
Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.
Catatan
- Setelah tugas dibuat, gunakan
task_idyang dikembalikan untuk mengkueri hasilnya.task_idberlaku selama 24 jam. Jangan membuat tugas duplikat. Sebagai gantinya, gunakan polling untuk mengambil hasilnya. - Untuk panduan pemula, lihat Panggil API dengan Postman atau cURL.
Parameter permintaanContent-Type Tipe konten permintaan. Harus Authorization Mengautentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx. X-DashScope-Async Mengaktifkan pemrosesan asinkron. Permintaan HTTP hanya mendukung panggilan asinkron. Harus PentingJika header permintaan ini tidak ada, kesalahan "current user api does not support synchronous calls" akan dikembalikan. Isi permintaanmodel Nama model. Nilai contoh: wan2.7-videoedit. input Parameter input, termasuk prompt. parameters Parameter untuk pemrosesan video, seperti resolusi, durasi, penulisan ulang prompt cerdas, dan watermark. | |
Parameter responsoutput Berisi output tugas. request_id Identifier permintaan unik untuk pelacakan dan troubleshooting. code Kode kesalahan. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan. message Pesan kesalahan detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan. | Respons berhasilSimpan Respons kesalahanPembuatan tugas gagal. Lihat Kode kesalahan. |
Langkah 2: Kueri hasilnya
Singapura
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Beijing
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.
Catatan
- Rekomendasi polling: Pembuatan video memerlukan beberapa menit. Gunakan mekanisme polling dengan interval yang masuk akal, misalnya 15 detik.
- Transisi status tugas: PENDING → RUNNING → SUCCEEDED atau FAILED.
- Tautan hasil: Setelah tugas berhasil, URL video yang berlaku selama 24 jam dikembalikan. Unduh dan simpan video ke penyimpanan permanen, seperti OSS.
task_idmasa berlaku: 24 jam. Setelah periode ini, kueri akan mengembalikan status tugas sebagaiUNKNOWN.
Parameter permintaanHeaderAuthorization Mengautentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx. Parameter jalurtask_id ID tugas. | Kueri hasilGanti |
Parameter responsoutput Berisi output tugas. usage Statistik penggunaan untuk penagihan. Hanya ditagih untuk tugas yang berhasil. request_id Identifier permintaan unik untuk pelacakan dan troubleshooting. | Tugas berhasilURL video hanya berlaku selama 24 jam, lalu secara otomatis dihapus. Segera simpan video yang dihasilkan. Tugas gagalSaat tugas gagal, Kueri kedaluwarsa
|
DashScope SDK
Nama parameter dalam SDK sebagian besar konsisten dengan API HTTP, tetapi struktur parameternya mengikuti konvensi masing-masing bahasa.
Pengeditan video biasanya memerlukan waktu 1 hingga 5 menit. SDK menangani proses panggilan HTTP asinkron secara internal, mendukung panggilan sinkron maupun asinkron.
Waktu pemrosesan aktual bergantung pada jumlah tugas dalam antrian dan status layanan. Tunggu hingga hasil selesai.
SDK Python
PentingPastikan Anda menggunakan SDK Python DashScope versi 1.25.16 atau lebih baru.
Menggunakan versi lama mungkin memicu kesalahan seperti "url error, please check url!". Lihat Instal SDK untuk memperbarui versi Anda.
Tetapkan base_http_api_url berdasarkan wilayah layanan:
Singapura
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
China (Beijing)
dashscope.base_http_api_url = 'https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1'
Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.
Panggilan sinkron
Contoh permintaan
import base64
import mimetypes
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os
# URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Jika variabel lingkungan DASHSCOPE_API_KEY belum disetel, masukkan Kunci API Model Studio Anda di sini: api_key="sk-xxx"
# Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Format: data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Format gambar tidak didukung atau tidak dikenali.")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
# Parameter reference_image_url mendukung tiga metode input berikut.
# Metode 1: Gunakan URL publik gambar.
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"
# Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
# Format: file:// + jalur file
# Contoh (jalur absolut):
# reference_image_url = "file://" + "/path/to/image.png" # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png" # Windows
# Contoh (jalur relatif):
# reference_image_url = "file://" + "./image.png" # Relatif terhadap lokasi skrip saat ini.
# Metode 3: String Base64 terenkripsi.
# reference_image_url = encode_file("/path/to/image.png")
def sample_sync_call_videoedit():
# Panggil API secara sinkron untuk langsung menerima hasilnya.
print('Please wait...')
rsp = VideoSynthesis.call(
api_key=api_key,
model='wan2.7-videoedit',
prompt='Replace the clothes of the girl in the video with the clothes from the image.',
media=[
{
"type": "video",
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
},
{
"type": "reference_image",
"url": reference_image_url
}
],
resolution='720P',
prompt_extend=True,
watermark=True)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.video_url)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
sample_sync_call_videoedit()
Contoh respons
video_urlberlaku selama 24 jam. Segera unduh video tersebut.
{
"status_code": 200,
"request_id": "d6c3c865-34e9-98a9-a53d-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "1de7c853-755a-454a-91bc-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
"submit_time": "2026-04-10 17:16:30.821",
"scheduled_time": "2026-04-10 17:16:46.379",
"end_time": "2026-04-10 17:24:59.352",
"orig_prompt": "Ganti pakaian gadis dalam video dengan pakaian dari gambar."
},
"usage": {
"video_count": 1,
"video_duration": 0,
"video_ratio": "",
"duration": 10.08,
"input_video_duration": 5.04,
"output_video_duration": 5.04,
"SR": 720
}
}
Panggilan asinkron
Contoh permintaan
import base64
import mimetypes
from http import HTTPStatus
from dashscope import VideoSynthesis
import dashscope
import os
# URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# Jika variabel lingkungan DASHSCOPE_API_KEY belum disetel, masukkan Kunci API Model Studio Anda di sini: api_key="sk-xxx"
# Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Format: data:{MIME_type};base64,{base64_data}
def encode_file(file_path):
mime_type, _ = mimetypes.guess_type(file_path)
if not mime_type or not mime_type.startswith("image/"):
raise ValueError("Format gambar tidak didukung atau tidak dikenali.")
with open(file_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
return f"data:{mime_type};base64,{encoded_string}"
# Parameter reference_image_url mendukung tiga metode input berikut.
# Metode 1: Gunakan URL publik gambar.
reference_image_url = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png"
# Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
# Format: file:// + jalur file
# Contoh (jalur absolut):
# reference_image_url = "file://" + "/path/to/image.png" # Linux/macOS
# reference_image_url = "file://" + "C:/path/to/image.png" # Windows
# Contoh (jalur relatif):
# reference_image_url = "file://" + "./image.png" # Relatif terhadap lokasi skrip saat ini.
# Metode 3: String Base64 terenkripsi.
# reference_image_url = encode_file("/path/to/image.png")
def sample_async_call_videoedit():
# Panggil API asinkron, yang mengembalikan informasi tugas.
# Anda kemudian dapat memeriksa status tugas menggunakan ID tugas yang dikembalikan.
rsp = VideoSynthesis.async_call(
api_key=api_key,
model='wan2.7-videoedit',
prompt='Replace the clothes of the girl in the video with the clothes from the image.',
media=[
{
"type": "video",
"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4"
},
{
"type": "reference_image",
"url": reference_image_url
}
],
resolution='720P',
prompt_extend=True,
watermark=True)
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))
# Dapatkan informasi tugas, termasuk status tugas.
status = VideoSynthesis.fetch(task=rsp, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status) # Periksa status tugas.
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# Tunggu hingga tugas selesai. Metode ini melakukan polling secara berkala hingga tugas selesai.
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_videoedit()
Contoh respons
- Respons pembuatan tugas
{
"status_code": 200,
"request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
"code": "",
"message": "",
"output": {
"task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
"task_status": "PENDING",
"video_url": ""
},
"usage": null
}
-
Respons kueri tugas
video_urlberlaku selama 24 jam. Segera unduh video tersebut.
{
"status_code": 200,
"request_id": "d6c3c865-34e9-98a9-a53d-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "1de7c853-755a-454a-91bc-xxxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxxx",
"submit_time": "2026-04-10 17:16:30.821",
"scheduled_time": "2026-04-10 17:16:46.379",
"end_time": "2026-04-10 17:24:59.352",
"orig_prompt": "Ganti pakaian perempuan di dalam video dengan pakaian dari gambar."
},
"usage": {
"video_count": 1,
"video_duration": 0,
"video_ratio": "",
"duration": 10.08,
"input_video_duration": 5.04,
"output_video_duration": 5.04,
"SR": 720
}
}
SDK Java
PentingPastikan Anda menggunakan SDK Java DashScope versi 2.22.14 atau lebih baru.
Menggunakan versi lama mungkin memicu kesalahan seperti "url error, please check url!". Lihat Instal SDK untuk memperbarui versi Anda.
Tetapkan Constants.baseHttpApiUrl berdasarkan wilayah layanan:
Singapura
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
China (Beijing)
Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
Ganti {WorkspaceId} dengan ID ruang kerja aktual Anda.
Panggilan sinkron
Contoh permintaan
// Copyright (c) Alibaba, Inc. and its affiliates.
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
public class VideoEdit {
static {
// URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// Jika variabel lingkungan DASHSCOPE_API_KEY tidak disetel, masukkan Kunci API Model Studio Anda di sini: apiKey="sk-xxx"
// Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
public static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// Parameter referenceImageUrl mendukung tiga metode input berikut.
// Metode 1: Gunakan URL publik gambar.
static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";
// Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
// Format: file:// + jalur file
// Contoh (jalur absolut):
// static String referenceImageUrl = "file://" + "/path/to/image.png"; // Linux/macOS
// static String referenceImageUrl = "file://" + "C:/path/to/image.png"; // Windows
// Contoh (jalur relatif):
// static String referenceImageUrl = "file://" + "./image.png"; // Relatif terhadap direktori eksekusi saat ini.
// Metode 3: Gunakan enkode Base64.
// static String referenceImageUrl = encodeFile("/path/to/image.png");
// Formatnya adalah data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("File does not exist: " + filePath);
}
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot detect file type: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("Unsupported or unrecognized image format.");
}
byte[] fileBytes = null;
try {
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file content: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
add(VideoSynthesisParam.Media.builder()
.url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4")
.type("video")
.build());
add(VideoSynthesisParam.Media.builder()
.url(referenceImageUrl)
.type("reference_image")
.build());
}};
Map<String, Object> parameters = new HashMap<>();
parameters.put("resolution", "720P");
parameters.put("prompt_extend", true);
parameters.put("watermark", true);
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.7-videoedit")
.prompt("Replace the clothes of the girl in the video with the clothes from the image.")
.media(media)
.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 {
videoEdit();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Contoh respons
video_urlberlaku selama 24 jam. Segera unduh video tersebut.
{
"request_id": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
"output": {
"task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
"orig_prompt": "Replace the clothes of the girl in the video with the clothes from the image.",
"submit_time": "2026-04-10 17:21:01.719",
"scheduled_time": "2026-04-10 17:21:13.182",
"end_time": "2026-04-10 17:31:41.286"
},
"usage": {
"video_count": 1,
"duration": 10,08,
"input_video_duration": 5,04,
"output_video_duration": 5,04,
"SR": "720"
},
"status_code": 200,
"code": "",
"message": ""
}
Panggilan asinkron
Contoh permintaan
// Copyright (c) Alibaba, Inc. and its affiliates.
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.aigc.videosynthesis.VideoSynthesisListResult;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
public class VideoEdit {
static {
// URL berikut berlaku untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja Anda yang sebenarnya. URL bervariasi tergantung wilayah.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// Jika variabel lingkungan DASHSCOPE_API_KEY tidak disetel, masukkan Kunci API Model Studio Anda di sini: apiKey="sk-xxx"
// Kunci API bersifat spesifik per wilayah. Untuk mendapatkan Kunci API, kunjungi https://www.alibabacloud.com/help/en/model-studio/get-api-key
public static String apiKey = System.getenv("DASHSCOPE_API_KEY");
// Parameter referenceImageUrl mendukung tiga metode input berikut.
// Metode 1: Gunakan URL publik gambar.
static String referenceImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260402/fwjpqf/wan2.7-videoedit-change-clothes.png";
// Metode 2: Gunakan file lokal (jalur absolut maupun relatif didukung).
// Format: file:// + jalur file
// Contoh (jalur absolut):
// static String referenceImageUrl = "file://" + "/path/to/image.png"; # Linux/macOS
// static String referenceImageUrl = "file://" + "C:/path/to/image.png"; # Windows
// Contoh (jalur relatif):
// static String referenceImageUrl = "file://" + "./image.png"; # Relatif terhadap direktori eksekusi saat ini.
// Metode 3: Gunakan enkode Base64.
// static String referenceImageUrl = encodeFile("/path/to/image.png");
// Formatnya adalah data:{MIME_type};base64,{base64_data}
public static String encodeFile(String filePath) {
Path path = Paths.get(filePath);
if (!Files.exists(path)) {
throw new IllegalArgumentException("File does not exist: " + filePath);
}
String mimeType = null;
try {
mimeType = Files.probeContentType(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot detect file type: " + filePath);
}
if (mimeType == null || !mimeType.startsWith("image/")) {
throw new IllegalArgumentException("Unsupported or unrecognized image format.");
}
byte[] fileBytes = null;
try {
fileBytes = Files.readAllBytes(path);
} catch (IOException e) {
throw new IllegalArgumentException("Cannot read file content: " + filePath);
}
String encodedString = Base64.getEncoder().encodeToString(fileBytes);
return "data:" + mimeType + ";base64," + encodedString;
}
public static void videoEdit() throws ApiException, NoApiKeyException, InputRequiredException {
VideoSynthesis vs = new VideoSynthesis();
List<VideoSynthesisParam.Media> media = new ArrayList<VideoSynthesisParam.Media>(){{
add(VideoSynthesisParam.Media.builder()
.url("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20260403/nlspwm/T2VA_22.mp4")
.type("video")
.build());
add(VideoSynthesisParam.Media.builder()
.url(referenceImageUrl)
.type("reference_image")
.build());
}};
Map<String, Object> parameters = new HashMap<>();
parameters.put("resolution", "720P");
parameters.put("prompt_extend", true);
parameters.put("watermark", true);
VideoSynthesisParam param =
VideoSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.7-videoedit")
.prompt("Replace the clothes of the girl in the video with the clothes from the image.")
.media(media)
.parameters(parameters)
.build();
// Lakukan panggilan asinkron.
VideoSynthesisResult task = vs.asyncCall(param);
System.out.println(JsonUtils.toJson(task));
System.out.println("Please wait...");
// Tunggu hingga tugas selesai dan ambil hasil akhirnya.
VideoSynthesisResult result = vs.wait(task, apiKey);
System.out.println(JsonUtils.toJson(result));
}
// Ambil daftar tugas.
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);
}
// Ambil hasil satu tugas.
public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
VideoSynthesis is = new VideoSynthesis();
// apiKey bisa null jika variabel lingkungan DASHSCOPE_API_KEY telah disetel.
VideoSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args) {
try {
videoEdit();
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Contoh respons
- Respons pembuatan tugas
{
"request_id": "f16ae7e9-d518-92f8-a02c-xxxxxx",
"output": {
"task_id": "05e68c7e-850c-49e4-b866-xxxxxx",
"task_status": "PENDING",
"video_url": ""
},
"usage": null,
"status_code": 200,
"code": "",
"message": ""
}
-
Respons kueri tugas
video_urlberlaku selama 24 jam. Segera unduh video tersebut.
{
"request_id": "0a15ad3c-cde7-9f7e-b8d2-xxxxxx",
"output": {
"task_id": "0025d1e1-009a-4f53-9c27-xxxxx",
"task_status": "SUCCEEDED",
"video_url": "https://dashscope-a717.oss-accelerate.aliyuncs.com/xxx.mp4?Expires=xxx",
"orig_prompt": "Replace the clothes of the girl in the video with the clothes from the image.",
"submit_time": "2026-04-10 17:21:01.719",
"scheduled_time": "2026-04-10 17:21:13.182",
"end_time": "2026-04-10 17:31:41.286"
},
"usage": {
"video_count": 1,
"duration": 10,08,
"input_video_duration": 5,04,
"output_video_duration": 5,04,
"SR": "720"
},
"status_code": 200,
"code": "",
"message": ""
}
Kode kesalahan
Jika panggilan model gagal, lihat Kode kesalahan untuk troubleshooting.