All Products
Search
Document Center

Alibaba Cloud Model Studio:Terjemahan File Audio dan Video – Qwen

Last Updated:Jul 09, 2026

qwen3-livetranslate-flash menerjemahkan file audio dan video ke dalam 18 bahasa. Model ini menerima input audio atau video dan mengembalikan teks terjemahan, audio tersintesis, atau keduanya melalui API streaming. Untuk input video, konteks visual meningkatkan akurasi terjemahan (misalnya, membedakan antara "medical mask" dan "masquerade mask" berdasarkan frame video).

Sebelum memulai

  1. Buat Kunci API.

  2. Konfigurasikan Kunci API sebagai Variabel lingkungan.

  3. (Opsional) Jika Anda menggunakan OpenAI SDK, instal SDK.

Memulai dengan cepat

Semua contoh menggunakan API streaming yang kompatibel dengan OpenAI. Tetapkan bahasa sumber dan target melalui translation_options. Input default adalah audio; hapus komentar pada blok input video di setiap contoh untuk menerjemahkan file video.

Menentukan source_lang meningkatkan akurasi. Abaikan parameter ini untuk mengaktifkan deteksi bahasa otomatis.
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# --- Input audio ---
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "input_audio",
                "input_audio": {
                    "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    "format": "wav",
                },
            }
        ],
    }
]

# --- Input video (hapus komentar untuk menggunakan) ---
# messages = [
#     {
#         "role": "user",
#         "content": [
#             {
#                 "type": "video_url",
#                 "video_url": {
#                     "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
#                 },
#             }
#         ],
#     },
# ]

completion = client.chat.completions.create(
    model="qwen3-livetranslate-flash",
    messages=messages,
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    stream=True,
    stream_options={"include_usage": True},
    # translation_options bukan parameter standar OpenAI; lewatkan melalui extra_body
    extra_body={"translation_options": {"source_lang": "zh", "target_lang": "en"}},
)

for chunk in completion:
    print(chunk)
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});

// --- Input audio ---
const messages = [
    {
        role: "user",
        content: [
            {
                type: "input_audio",
                input_audio: {
                    data: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    format: "wav",
                },
            },
        ],
    },
];

// --- Input video (hapus komentar untuk menggunakan) ---
// const messages = [
//     {
//         role: "user",
//         content: [
//             {
//                 type: "video_url",
//                 video_url: {
//                     url: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4",
//                 },
//             },
//         ],
//     },
// ];

async function main() {
    const completion = await client.chat.completions.create({
        model: "qwen3-livetranslate-flash",
        messages: messages,
        modalities: ["text", "audio"],
        audio: { voice: "Cherry", format: "wav" },
        stream: true,
        stream_options: { include_usage: true },
        translation_options: { source_lang: "zh", target_lang: "en" },
    });

    for await (const chunk of completion) {
        console.log(JSON.stringify(chunk));
    }
}

main();
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-livetranslate-flash",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {
                        "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                        "format": "wav"
                    }
                }
            ]
        }
    ],
    "modalities": ["text", "audio"],
    "audio": {
        "voice": "Cherry",
        "format": "wav"
    },
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "translation_options": {
        "source_lang": "zh",
        "target_lang": "en"
    }
}'

Contoh-contoh ini menggunakan URL file publik. Untuk menggunakan file lokal, lihat Input file lokal yang dikodekan Base64.

Parameter permintaan

Input

Array messages harus berisi tepat satu pesan dengan role diatur ke user. Bidang content berisi audio atau video yang akan diterjemahkan:

  • Audio: Atur type ke input_audio. Berikan URL file atau data yang dikodekan Base64 di input_audio.data, dan tentukan formatnya (misalnya, wav) di input_audio.format.

  • Video: Atur type ke video_url. Berikan URL file di video_url.url.

Opsi terjemahan

Tentukan bahasa sumber dan target dalam parameter translation_options:

"translation_options": {"source_lang": "zh", "target_lang": "en"}

Pada Python SDK, translation_options bukan parameter standar OpenAI. Lewatkan melalui extra_body:

extra_body={"translation_options": {"source_lang": "zh", "target_lang": "en"}}

Modalitas output

Kendalikan format output dengan parameter modalities:

modalities Output
["text"] Hanya teks terjemahan
["text", "audio"] Teks terjemahan dan audio tersintesis yang dikodekan Base64

Jika output mencakup audio, atur suara dalam parameter audio. Lihat Suara yang didukung untuk opsi yang tersedia.

Batasan

  • Hanya satu giliran: Model menangani satu terjemahan per permintaan. Percakapan multi-giliran tidak didukung.

  • Tidak ada pesan sistem: Peran system tidak didukung.

  • Hanya streaming: Hanya output streaming yang kompatibel dengan OpenAI yang didukung.

Uraikan respons

Setiap objek chunk streaming berisi:

  • Teks: chunk.choices[0].delta.content

  • Audio: chunk.choices[0].delta.audio["data"] (dikodekan Base64, laju sampel 24 kHz)

Simpan audio ke file

Gabungkan semua fragmen audio Base64 dari aliran, lalu dekode dan simpan hasilnya setelah aliran selesai.

Python

import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "input_audio",
                "input_audio": {
                    "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    "format": "wav",
                },
            }
        ],
    }
]

completion = client.chat.completions.create(
    model="qwen3-livetranslate-flash",
    messages=messages,
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    stream=True,
    stream_options={"include_usage": True},
    extra_body={"translation_options": {"source_lang": "zh", "target_lang": "en"}},
)

# Gabungkan fragmen Base64, lalu dekode setelah aliran selesai
audio_string = ""
for chunk in completion:
    if chunk.choices:
        if hasattr(chunk.choices[0].delta, "audio"):
            try:
                audio_string += chunk.choices[0].delta.audio["data"]
            except Exception as e:
                print(chunk.choices[0].delta.audio["transcript"])
    else:
        print(chunk.usage)

wav_bytes = base64.b64decode(audio_string)
audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
sf.write("output.wav", audio_np, samplerate=24000)

Node.js

import OpenAI from "openai";
import { createWriteStream } from "node:fs";
import { Writer } from "wav";

const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});

const messages = [
    {
        role: "user",
        content: [
            {
                type: "input_audio",
                input_audio: {
                    data: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    format: "wav",
                },
            },
        ],
    },
];

const completion = await client.chat.completions.create({
    model: "qwen3-livetranslate-flash",
    messages: messages,
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" },
    stream: true,
    stream_options: { include_usage: true },
    translation_options: { source_lang: "zh", target_lang: "en" },
});

// Gabungkan fragmen Base64, lalu dekode setelah aliran selesai
let audioString = "";
for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        if (chunk.choices[0].delta.audio?.data) {
            audioString += chunk.choices[0].delta.audio.data;
        }
    } else {
        console.log(chunk.usage);
    }
}

// Simpan sebagai file WAV
async function saveAudio(base64Data, outputPath) {
    const wavBuffer = Buffer.from(base64Data, "base64");
    const writer = new Writer({
        sampleRate: 24000,
        channels: 1,
        bitDepth: 16,
    });
    const outputStream = createWriteStream(outputPath);
    writer.pipe(outputStream);
    writer.write(wavBuffer);
    writer.end();
    await new Promise((resolve, reject) => {
        outputStream.on("finish", resolve);
        outputStream.on("error", reject);
    });
    console.log(`Audio disimpan ke ${outputPath}`);
}

saveAudio(audioString, "output.wav");

Pemutaran real-time

Dekode setiap fragmen Base64 saat tiba dan putar langsung. Pendekatan ini memerlukan pustaka audio khusus platform.

Python

Instal pyaudio terlebih dahulu:

Platform Instalasi
macOS brew install portaudio && pip install pyaudio
Ubuntu / Debian sudo apt-get install python-pyaudio python3-pyaudio atau pip install pyaudio
CentOS sudo yum install -y portaudio portaudio-devel && pip install pyaudio
Windows python -m pip install pyaudio
import os
from openai import OpenAI
import base64
import numpy as np
import pyaudio
import time

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "input_audio",
                "input_audio": {
                    "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    "format": "wav",
                },
            }
        ],
    }
]

completion = client.chat.completions.create(
    model="qwen3-livetranslate-flash",
    messages=messages,
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    stream=True,
    stream_options={"include_usage": True},
    extra_body={"translation_options": {"source_lang": "zh", "target_lang": "en"}},
)

# Inisialisasi PyAudio untuk pemutaran real-time
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)

for chunk in completion:
    if chunk.choices:
        if hasattr(chunk.choices[0].delta, "audio"):
            try:
                audio_data = chunk.choices[0].delta.audio["data"]
                wav_bytes = base64.b64decode(audio_data)
                audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
                stream.write(audio_np.tobytes())
            except Exception as e:
                print(chunk.choices[0].delta.audio["transcript"])

time.sleep(0.8)
stream.stop_stream()
stream.close()
p.terminate()

Node.js

Instal dependensi terlebih dahulu:

Platform Instalasi
macOS brew install portaudio && npm install speaker
Ubuntu / Debian sudo apt-get install libasound2-dev && npm install speaker
Windows npm install speaker
import OpenAI from "openai";
import Speaker from "speaker";

const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // URL berikut untuk wilayah Singapura. Saat memanggil, ganti {WorkspaceId} dengan ID ruang kerja aktual Anda. URL berbeda-beda tergantung wilayah.
    baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});

const messages = [
    {
        role: "user",
        content: [
            {
                type: "input_audio",
                input_audio: {
                    data: "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                    format: "wav",
                },
            },
        ],
    },
];

const completion = await client.chat.completions.create({
    model: "qwen3-livetranslate-flash",
    messages: messages,
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" },
    stream: true,
    stream_options: { include_usage: true },
    translation_options: { source_lang: "zh", target_lang: "en" },
});

// Streaming audio ke speaker secara real-time
const speaker = new Speaker({
    sampleRate: 24000,
    channels: 1,
    bitDepth: 16,
    signed: true,
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        if (chunk.choices[0].delta.audio?.data) {
            const pcmBuffer = Buffer.from(chunk.choices[0].delta.audio.data, "base64");
            speaker.write(pcmBuffer);
        }
    } else {
        console.log(chunk.usage);
    }
}

speaker.on("finish", () => console.log("Pemutaran selesai"));
speaker.end();

Penagihan

Audio

Setiap detik audio input atau output mengonsumsi 12,5 token. Audio yang durasinya kurang dari 1 detik ditagih sebagai 1 detik.

Video

Konsumsi token video memiliki dua komponen:

  • Token audio: 12,5 token per detik audio. Audio yang durasinya kurang dari 1 detik ditagih sebagai 1 detik.

  • Token video: Dihitung berdasarkan jumlah frame dan resolusi. Rumusnya adalah:

      video_tokens = ceil(frame_count / 2) x (height / 32) x (width / 32) + 2

    Di mana:

    • Frame diambil pada 2 FPS, dibatasi dalam rentang [4, 128].

    • Tinggi dan lebar disesuaikan menjadi kelipatan 32 piksel dan diskalakan secara dinamis agar sesuai dalam batas total piksel.

Skrip Python untuk menghitung token video

# Instal: pip install opencv-python
import math
import cv2

FRAME_FACTOR = 2
IMAGE_FACTOR = 32
MAX_RATIO = 200
VIDEO_MIN_PIXELS = 128 * 32 * 32
VIDEO_MAX_PIXELS = 768 * 32 * 32
FPS = 2
FPS_MIN_FRAMES = 4
FPS_MAX_FRAMES = 128
VIDEO_TOTAL_PIXELS = 16384 * 32 * 32

def round_by_factor(number, factor):
    return round(number / factor) * factor

def ceil_by_factor(number, factor):
    return math.ceil(number / factor) * factor

def floor_by_factor(number, factor):
    return math.floor(number / factor) * factor

def get_video(video_path):
    cap = cv2.VideoCapture(video_path)
    frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    video_fps = cap.get(cv2.CAP_PROP_FPS)
    cap.release()
    return frame_height, frame_width, total_frames, video_fps

def smart_nframes(total_frames, video_fps):
    min_frames = ceil_by_factor(FPS_MIN_FRAMES, FRAME_FACTOR)
    max_frames = floor_by_factor(min(FPS_MAX_FRAMES, total_frames), FRAME_FACTOR)
    duration = total_frames / video_fps if video_fps != 0 else 0
    if duration - int(duration) > (1 / FPS):
        total_frames = math.ceil(duration * video_fps)
    else:
        total_frames = math.ceil(int(duration) * video_fps)
    nframes = total_frames / video_fps * FPS
    nframes = int(min(min(max(nframes, min_frames), max_frames), total_frames))
    if not (FRAME_FACTOR <= nframes <= total_frames):
        raise ValueError(f"nframes harus dalam interval [{FRAME_FACTOR}, {total_frames}], tetapi mendapatkan {nframes}.")
    return nframes

def smart_resize(height, width, nframes, factor=IMAGE_FACTOR):
    min_pixels = VIDEO_MIN_PIXELS
    total_pixels = VIDEO_TOTAL_PIXELS
    max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
    if max(height, width) / min(height, width) > MAX_RATIO:
        raise ValueError(f"rasio aspek absolut harus lebih kecil dari {MAX_RATIO}, mendapatkan {max(height, width) / min(height, width)}")
    h_bar = max(factor, round_by_factor(height, factor))
    w_bar = max(factor, round_by_factor(width, factor))
    if h_bar * w_bar > max_pixels:
        beta = math.sqrt((height * width) / max_pixels)
        h_bar = floor_by_factor(height / beta, factor)
        w_bar = floor_by_factor(width / beta, factor)
    elif h_bar * w_bar < min_pixels:
        beta = math.sqrt(min_pixels / (height * width))
        h_bar = ceil_by_factor(height * beta, factor)
        w_bar = ceil_by_factor(width * beta, factor)
    return h_bar, w_bar

def video_token_calculate(video_path):
    height, width, total_frames, video_fps = get_video(video_path)
    nframes = smart_nframes(total_frames, video_fps)
    resized_height, resized_width = smart_resize(height, width, nframes)
    video_token = int(math.ceil(nframes / FPS) * resized_height / 32 * resized_width / 32)
    video_token += 2
    return video_token

if __name__ == "__main__":
    video_path = "spring_mountain.mp4"  # Ganti dengan path video Anda
    video_token = video_token_calculate(video_path)
    print("video_tokens:", video_token)

Untuk harga berdasarkan token, lihat Daftar model.

Detail model

Model Versi Jendela konteks Input maksimum Output maksimum
qwen3-livetranslate-flash Stable 53.248 token 49.152 token 4.096 token
qwen3-livetranslate-flash-2025-12-01 Snapshot 53.248 token 49.152 token 4.096 token
qwen3-livetranslate-flash saat ini memiliki kemampuan yang sama dengan qwen3-livetranslate-flash-2025-12-01.

Bahasa yang didukung

Gunakan kode bahasa ini untuk source_lang dan target_lang. Beberapa bahasa target hanya mendukung output teks.

Kode bahasa Bahasa Output yang didukung
en Inggris Audio, teks
zh Tiongkok Audio, teks
ru Rusia Audio, teks
fr Prancis Audio, teks
de Jerman Audio, teks
pt Portugis Audio, teks
es Spanyol Audio, teks
it Italia Audio, teks
id Bahasa Indonesia Teks
ko Korea Audio, teks
ja Jepang Audio, teks
vi Vietnam Teks
th Thai Teks
ar Arab Teks
yue Kanton Audio, teks
hi Hindi Teks
el Yunani Teks
tr Turki Teks

Suara yang didukung

Atur parameter voice dalam audio ketika output mencakup audio tersintesis.

Nama suara voice parameter Deskripsi Bahasa yang didukung
Cherry Cherry Wanita muda yang ceria, ramah, dan tulus. Tiongkok, Inggris, Prancis, Jerman, Rusia, Italia, Spanyol, Portugis, Jepang, Korea
Nofish Nofish Seorang desainer yang kesulitan mengucapkan konsonan retrofleks. Tiongkok, Inggris, Prancis, Jerman, Rusia, Italia, Spanyol, Portugis, Jepang, Korea
Shanghai-Jada Jada Wanita energik dan riuh dari Shanghai. Tiongkok
Beijing-Dylan Dylan Pria muda yang tumbuh di hutong Beijing. Tiongkok
Sichuan-Sunny Sunny Gadis manis dari Sichuan. Tiongkok
Tianjin-Peter Peter Suara bergaya pelawak crosstalk Tianjin (peran pendukung). Tiongkok
Cantonese-Kiki Kiki Sahabat baik manis dari Hong Kong. Kanton
Sichuan-Eric Eric Pria dari Chengdu, Sichuan, yang tidak konvensional dan menonjol dari keramaian. Tiongkok

FAQ

Saat saya memasukkan file video, konten apa yang diterjemahkan?

Model menerjemahkan trek audio video tersebut. Informasi visual meningkatkan akurasi terjemahan.

Misalnya, jika audionya mengatakan "This is a mask":

  • Jika video menampilkan masker medis, model menerjemahkannya sebagai "This is a medical mask."

  • Saat video menampilkan topeng masquerade, model menerjemahkannya menjadi "Ini adalah topeng masquerade."

Referensi API

Untuk detail lengkap parameter input dan output, lihat Terjemahan audio dan video - Qwen.