All Products
Search
Document Center

Alibaba Cloud Model Studio:Kloning suara

Last Updated:Nov 23, 2026

Unggah rekaman untuk membuat suara, lalu gunakan dalam percakapan Qwen-Omni atau Qwen-Omni-Realtime. Panduan ini mencakup bahasa yang didukung, persyaratan audio, langkah kloning, penagihan, dan pengelolaan suara.

Untuk parameter permintaan, respons, dan kesalahan, lihat Referensi API kloning suara.

PentingDokumen ini membahas API kloning suara untuk Qwen-Omni dan Qwen-Omni-Realtime. Untuk model sintesis ucapan, lihat Panduan kloning suara.

PentingDomain khusus workspace tersedia di wilayah Singapura. Domain ini meningkatkan performa dan stabilitas inferensi. Kami menyarankan migrasi ke domain berikut:

  • Singapura: dari https://dashscope-intl.aliyuncs.com ke https://WorkspaceId.ap-southeast-1.maas.aliyuncs.com

Temukan WorkspaceId pada halaman Workspace Details di konsol Alibaba Cloud Model Studio. Domain lama tetap berfungsi.

Persyaratan audio

Kualitas rekaman memengaruhi hasil kloning.

Suara sistem dan kloning suara mendukung dialek yang berbeda. Tabel berikut mencantumkan bahasa dan dialek untuk kloning suara. Untuk suara sistem, lihat Daftar suara.

Item

Persyaratan

Format yang didukung

WAV (16-bit), MP3, M4A

Durasi

Disarankan 10 hingga 20 detik. Maksimum: 60 detik.

Ukuran file

< 10 MB

Laju sampel

>= 24 kHz

Kanal

Mono

Konten

Audio harus berisi setidaknya 3 detik ucapan yang jelas dan berkesinambungan tanpa suara latar. Bagian sisanya dapat mencakup jeda singkat (<=2 detik). Hindari musik latar, kebisingan, atau suara lain di sepanjang audio. Gunakan audio ucapan normal sebagai input. Jangan unggah lagu atau audio nyanyian.

Bahasa

Tionghoa (zh), Inggris (en), Jerman (de), Italia (it), Portugis (pt), Spanyol (es), Jepang (ja), Korea (ko), Prancis (fr), Rusia (ru), Thai (th), Indonesia (id), Arab (ar), Ceko (cs), Denmark (da), Belanda (nl), Finlandia (fi), Ibrani (he), Hindi (hi), Islandia (is), Melayu (ms), Norwegia (no), Persia (fa), Polandia (pl), Swedia (sv), Tagalog (tl), Turki (tr), Urdu (ur), Vietnam (vi)

Dialek Tionghoa: Dongbei, Shannxi, Sichuan, Henan, Changsha, Tianjin, Hangzhou, Liaoning, Shenyang, Anshan

Mulai cepat

gambar

1. Alur kerja

Buat suara, lalu gunakan dalam panggilan model:

  1. Membuat suara

    Panggil API Buat suara dan unggah klip audio. Sistem menganalisis audio dan membuat suara kloning kustom. Anda harus menentukan target_model pada langkah ini untuk menyatakan model omni yang akan menggunakan suara tersebut.

    Jika sudah memiliki suara, Anda dapat melewati langkah ini dan melanjutkan ke langkah berikutnya. Panggil API Daftar suara untuk melihat suara yang tersedia.

  2. Menggunakan suara dalam percakapan

    Panggil API Omni, baik real-time maupun non-real-time, dengan suara yang telah dibuat. Model Omni harus sama dengan target_model.

2. Konfigurasi model dan prasyarat

Pilih model, lalu penuhi prasyaratnya.

Konfigurasi model

Kloning suara memerlukan dua model:

  • Model kloning suara: qwen-voice-enrollment

  • Model Omni yang menggunakan suara:

    • qwen3.8-omni-flash-realtime
    • qwen3.5-omni-plus-realtime
    • qwen3.5-omni-flash-realtime
    • qwen3.5-omni-plus
    • qwen3.5-omni-flash

Prasyarat

  1. Dapatkan API key: Dapatkan API key. Demi keamanan, konfigurasikan API key sebagai variabel lingkungan.
  2. Instal SDK: Instal SDK DashScope terbaru.
  3. Siapkan audio untuk kloning: Audio harus memenuhi Persyaratan audio.

3. Contoh menyeluruh

Contoh ini mengkloning suara dan menggunakannya dalam percakapan.

Prinsip utama: target_model yang ditentukan saat kloning harus sama dengan model pada panggilan API Omni berikutnya. Jika tidak, sintesis akan gagal. Ganti file contoh voice.mp3 dengan audio Anda sendiri.

Real-time

Berlaku untuk model Qwen-Omni-Realtime. Lihat Qwen-Omni-Realtime.

# Requirements: dashscope >= 1.26.5, pyaudio
import os
import requests
import base64
import pathlib
import time
import pyaudio
from dashscope.audio.qwen_omni import MultiModality, OmniRealtimeCallback, OmniRealtimeConversation
import dashscope
# Wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# ======= Configuration =======
DEFAULT_TARGET_MODEL = "qwen3.8-omni-flash-realtime"  # Must be the same model for cloning and conversation
DEFAULT_PREFERRED_NAME = "guanyu"
DEFAULT_AUDIO_MIME_TYPE = "audio/mpeg"
VOICE_FILE_PATH = "voice.mp3"  # Path to the local audio file for voice cloning

def create_voice(file_path: str,
                 target_model: str = DEFAULT_TARGET_MODEL,
                 preferred_name: str = DEFAULT_PREFERRED_NAME,
                 audio_mime_type: str = DEFAULT_AUDIO_MIME_TYPE) -> str:
    """
    Create a custom voice and return the voice parameter.
    """
    # API keys differ between the Singapore and Beijing regions. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If you haven't set an environment variable, replace the following line with: api_key = "sk-xxx"
    api_key = os.getenv("DASHSCOPE_API_KEY")

    file_path_obj = pathlib.Path(file_path)
    if not file_path_obj.exists():
        raise FileNotFoundError(f"Audio file not found: {file_path}")

    base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
    data_uri = f"data:{audio_mime_type};base64,{base64_str}"

    # URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
    url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/tts/customization"
    payload = {
        "model": "qwen-voice-enrollment",
        "parameters": {"voice_clone_mode": "normal"},
        "input": {
            "action": "create",
            "target_model": target_model,
            "preferred_name": preferred_name,
            "audio": {"data": data_uri}
        }
    }
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    resp = requests.post(url, json=payload, headers=headers)
    if resp.status_code != 200:
        raise RuntimeError(f"Failed to create voice: {resp.status_code}, {resp.text}")

    try:
        return resp.json()["output"]["voice"]
    except (KeyError, ValueError) as e:
        raise RuntimeError(f"Failed to parse voice response: {e}")

class SimpleCallback(OmniRealtimeCallback):
    def __init__(self, pya):
        self.pya = pya
        self.out = None
    def on_open(self):
        self.out = self.pya.open(
            format=pyaudio.paInt16,
            channels=1,
            rate=24000,
            output=True
        )
    def on_event(self, response):
        if response['type'] == 'response.audio.delta':
            self.out.write(base64.b64decode(response['delta']))
        elif response['type'] == 'conversation.item.input_audio_transcription.completed':
            print(f"[User] {response['transcript']}")
        elif response['type'] == 'response.audio_transcript.done':
            print(f"[LLM] {response['transcript']}")

if __name__ == '__main__':
    # If you haven't set an environment variable, replace the following line with: dashscope.api_key = "sk-xxx"
    dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
    # URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
    url = "wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime"

    # Step 1: Clone a voice
    voice = create_voice(VOICE_FILE_PATH)
    print(f"Voice cloning complete. Voice: {voice}")

    # Step 2: Start a real-time conversation with the cloned voice
    pya = pyaudio.PyAudio()
    callback = SimpleCallback(pya)
    conv = OmniRealtimeConversation(model=DEFAULT_TARGET_MODEL, callback=callback, url=url)
    conv.connect()
    conv.update_session(
        output_modalities=[MultiModality.AUDIO, MultiModality.TEXT],
        voice=voice  # Use the cloned voice
    )
    mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
    print("Conversation started. Speak into your microphone (Ctrl+C to exit)...")
    try:
        while True:
            audio_data = mic.read(3200, exception_on_overflow=False)
            conv.append_audio(base64.b64encode(audio_data).decode())
            time.sleep(0.01)
    except KeyboardInterrupt:
        conv.close()
        mic.close()
        callback.out.close()
        pya.terminate()
        print("\nConversation ended")
import com.alibaba.dashscope.audio.omni.*;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import javax.sound.sampled.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main {
    // ===== Constants =====
    // Use the same model for voice cloning and real-time conversation
    private static final String TARGET_MODEL = "qwen3.8-omni-flash-realtime";
    private static final String PREFERRED_NAME = "guanyu";
    // Relative path to the local audio file for voice cloning
    private static final String AUDIO_FILE = "voice.mp3";
    private static final String AUDIO_MIME_TYPE = "audio/mpeg";

    // Generate a data URI
    public static String toDataUrl(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        String encoded = Base64.getEncoder().encodeToString(bytes);
        return "data:" + AUDIO_MIME_TYPE + ";base64," + encoded;
    }

    // Call the API to create a voice
    public static String createVoice() throws Exception {
        // The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        // If you haven't configured the environment variable, replace the following line with: String apiKey = "sk-xxx"
        String apiKey = System.getenv("DASHSCOPE_API_KEY");

        String jsonPayload =
                "{"
                        + "\"model\": \"qwen-voice-enrollment\","
                        + "\"parameters\": {\"voice_clone_mode\": \"normal\"},"
                        + "\"input\": {"
                        +     "\"action\": \"create\","
                        +     "\"target_model\": \"" + TARGET_MODEL + "\","
                        +     "\"preferred_name\": \"" + PREFERRED_NAME + "\","
                        +     "\"audio\": {"
                        +         "\"data\": \"" + toDataUrl(AUDIO_FILE) + "\""
                        +     "}"
                        + "}"
                        + "}";

        // URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
        String url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/tts/customization";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", "Bearer " + apiKey);
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        try (OutputStream os = con.getOutputStream()) {
            os.write(jsonPayload.getBytes(StandardCharsets.UTF_8));
        }

        int status = con.getResponseCode();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(status >= 200 && status < 300 ? con.getInputStream() : con.getErrorStream(),
                        StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            if (status == 200) {
                JsonObject jsonObj = new Gson().fromJson(response.toString(), JsonObject.class);
                return jsonObj.getAsJsonObject("output").get("voice").getAsString();
            }
            throw new IOException("Failed to create voice: " + status + " - " + response);
        }
    }

    // Simple audio player
    static class SimpleAudioPlayer {
        private final SourceDataLine line;
        private final Queue<byte[]> audioQueue = new ConcurrentLinkedQueue<>();
        private final Thread playerThread;
        private final AtomicBoolean shouldStop = new AtomicBoolean(false);

        public SimpleAudioPlayer() throws LineUnavailableException {
            AudioFormat format = new AudioFormat(24000, 16, 1, true, false);
            line = AudioSystem.getSourceDataLine(format);
            line.open(format);
            line.start();
            playerThread = new Thread(() -> {
                while (!shouldStop.get()) {
                    byte[] audio = audioQueue.poll();
                    if (audio != null) {
                        line.write(audio, 0, audio.length);
                    } else {
                        try { Thread.sleep(10); } catch (InterruptedException ignored) {}
                    }
                }
            }, "AudioPlayer");
            playerThread.start();
        }

        public void play(String base64Audio) {
            audioQueue.add(Base64.getDecoder().decode(base64Audio));
        }

        public void close() {
            shouldStop.set(true);
            try { playerThread.join(1000); } catch (InterruptedException ignored) {}
            line.drain();
            line.close();
        }
    }

    public static void main(String[] args) {
        try {
            // 1. Voice cloning: create a custom voice
            String voice = createVoice();
            System.out.println("Voice cloning complete. Voice: " + voice);

            // 2. Use the cloned voice in a real-time conversation
            SimpleAudioPlayer player = new SimpleAudioPlayer();
            AtomicBoolean shouldStop = new AtomicBoolean(false);

            OmniRealtimeParam param = OmniRealtimeParam.builder()
                    .model(TARGET_MODEL)
                    // The API keys for the Singapore and Beijing regions are different. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
                    // If you haven't configured the environment variable, replace the following line with: .apikey("sk-xxx")
                    .apikey(System.getenv("DASHSCOPE_API_KEY"))
                    // URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
                    .url("wss://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api-ws/v1/realtime")
                    .build();

            OmniRealtimeConversation conversation = new OmniRealtimeConversation(param, new OmniRealtimeCallback() {
                @Override public void onOpen() { System.out.println("Connection established"); }
                @Override public void onClose(int code, String reason) {
                    System.out.println("Connection closed (" + code + "): " + reason);
                    shouldStop.set(true);
                }
                @Override public void onEvent(JsonObject event) {
                    String type = event.get("type").getAsString();
                    if ("response.audio.delta".equals(type)) {
                        player.play(event.get("delta").getAsString());
                    } else if ("conversation.item.input_audio_transcription.completed".equals(type)) {
                        System.out.println("[User] " + event.get("transcript").getAsString());
                    } else if ("response.audio_transcript.done".equals(type)) {
                        System.out.println("[LLM] " + event.get("transcript").getAsString());
                    }
                }
            });

            conversation.connect();
            conversation.updateSession(OmniRealtimeConfig.builder()
                    .modalities(Arrays.asList(OmniRealtimeModality.AUDIO, OmniRealtimeModality.TEXT))
                    .voice(voice)  // Use the cloned custom voice
                    .enableTurnDetection(true)
                    .enableInputAudioTranscription(true)
                    .build()
            );

            System.out.println("Conversation started. Speak into the microphone (Ctrl+C to exit)...");
            AudioFormat format = new AudioFormat(16000, 16, 1, true, false);
            TargetDataLine mic = AudioSystem.getTargetDataLine(format);
            mic.open(format);
            mic.start();

            ByteBuffer buffer = ByteBuffer.allocate(3200);
            while (!shouldStop.get()) {
                int bytesRead = mic.read(buffer.array(), 0, buffer.capacity());
                if (bytesRead > 0) {
                    conversation.appendAudio(Base64.getEncoder().encodeToString(buffer.array()));
                }
                Thread.sleep(20);
            }

            conversation.close(1000, "Normal exit");
            player.close();
            mic.close();
            System.out.println("\nConversation ended");
        } catch (NoApiKeyException e) {
            System.err.println("API KEY not found. Set the DASHSCOPE_API_KEY environment variable.");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

Non-real-time

Berlaku untuk model Qwen3.5-Omni. Lihat Non-real-time (Qwen-Omni).

# Requirements: dashscope >= 1.23.9, soundfile, numpy
import os
import requests
import base64
import pathlib
import numpy as np
import soundfile as sf
import dashscope
# Wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# ======= Configuration =======
DEFAULT_TARGET_MODEL = "qwen3.5-omni-plus"  # Voice cloning and non-realtime calls must use the same model
DEFAULT_PREFERRED_NAME = "guanyu"
DEFAULT_AUDIO_MIME_TYPE = "audio/mpeg"
VOICE_FILE_PATH = "voice.mp3"  # Path to the local audio file for voice cloning

def create_voice(file_path: str,
                 target_model: str = DEFAULT_TARGET_MODEL,
                 preferred_name: str = DEFAULT_PREFERRED_NAME,
                 audio_mime_type: str = DEFAULT_AUDIO_MIME_TYPE) -> str:
    """
    Create a custom voice and return the voice parameter.
    """
    # API keys differ between Singapore and Beijing regions. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    # If the environment variable is not configured, replace the following line with: api_key = "sk-xxx"
    api_key = os.getenv("DASHSCOPE_API_KEY")

    file_path_obj = pathlib.Path(file_path)
    if not file_path_obj.exists():
        raise FileNotFoundError(f"Audio file not found: {file_path}")

    base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
    data_uri = f"data:{audio_mime_type};base64,{base64_str}"

    # URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
    url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/tts/customization"
    payload = {
        "model": "qwen-voice-enrollment",
        "input": {
            "action": "create",
            "target_model": target_model,
            "preferred_name": preferred_name,
            "audio": {"data": data_uri}
        }
    }
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }

    resp = requests.post(url, json=payload, headers=headers)
    if resp.status_code != 200:
        raise RuntimeError(f"Failed to create voice: {resp.status_code}, {resp.text}")

    try:
        return resp.json()["output"]["voice"]
    except (KeyError, ValueError) as e:
        raise RuntimeError(f"Failed to parse voice response: {e}")

if __name__ == '__main__':
    # URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
    dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

    # 1. Voice cloning: create a custom voice
    voice = create_voice(VOICE_FILE_PATH)
    print(f"Voice cloning complete. Voice: {voice}")

    # 2. Non-realtime conversation with the cloned voice
    messages = [{"role": "user", "content": [{"text": "Hello, please introduce yourself"}]}]

    response = dashscope.MultiModalConversation.call(
        # If the environment variable is not configured, replace with: api_key="sk-xxx"
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model=DEFAULT_TARGET_MODEL,
        messages=messages,
        modalities=["text", "audio"],
        audio={"voice": voice, "format": "wav"},  # Use the cloned voice
        stream=True
    )

    print("Model response:")
    audio_base64_string = ""
    for r in response:
        try:
            content = r.output.choices[0].message.content
            for item in content:
                if isinstance(item, dict):
                    if "audio" in item:
                        audio_base64_string += item["audio"].get("data", "")
                    elif "text" in item:
                        print(item["text"], end="")
        except Exception:
            pass

    if audio_base64_string:
        wav_bytes = base64.b64decode(audio_base64_string)
        audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
        sf.write("audio_cloned.wav", audio_np, samplerate=24000)
        print("\nAudio saved to: audio_cloned.wav")
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class Main {
    // ===== Constants =====
    // Voice cloning and non-realtime calls must use the same model
    private static final String TARGET_MODEL = "qwen3.5-omni-plus";
    private static final String PREFERRED_NAME = "guanyu";
    // Path to the local audio file for voice cloning
    private static final String AUDIO_FILE = "voice.mp3";
    private static final String AUDIO_MIME_TYPE = "audio/mpeg";

    // Write PCM data as a standard WAV file
    public static void writeWav(String path, byte[] pcmData, int sampleRate) throws IOException {
        int channels = 1, bitsPerSample = 16;
        int byteRate = sampleRate * channels * bitsPerSample / 8;
        int blockAlign = channels * bitsPerSample / 8;
        ByteBuffer header = ByteBuffer.allocate(44).order(ByteOrder.LITTLE_ENDIAN);
        header.put("RIFF".getBytes()); header.putInt(36 + pcmData.length);
        header.put("WAVE".getBytes()); header.put("fmt ".getBytes());
        header.putInt(16); header.putShort((short) 1); header.putShort((short) channels);
        header.putInt(sampleRate); header.putInt(byteRate);
        header.putShort((short) blockAlign); header.putShort((short) bitsPerSample);
        header.put("data".getBytes()); header.putInt(pcmData.length);
        try (FileOutputStream fos = new FileOutputStream(path)) {
            fos.write(header.array());
            fos.write(pcmData);
        }
    }

    // Generate a data URI from a file
    public static String toDataUrl(String filePath) throws IOException {
        byte[] bytes = Files.readAllBytes(Paths.get(filePath));
        String encoded = Base64.getEncoder().encodeToString(bytes);
        return "data:" + AUDIO_MIME_TYPE + ";base64," + encoded;
    }

    // Call the API to create a voice
    public static String createVoice() throws Exception {
        // API keys differ between Singapore and Beijing regions. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        // If the environment variable is not configured, replace the following line with: String apiKey = "sk-xxx"
        String apiKey = System.getenv("DASHSCOPE_API_KEY");

        String jsonPayload =
                "{"
                        + "\"model\": \"qwen-voice-enrollment\","
                        + "\"input\": {"
                        +     "\"action\": \"create\","
                        +     "\"target_model\": \"" + TARGET_MODEL + "\","
                        +     "\"preferred_name\": \"" + PREFERRED_NAME + "\","
                        +     "\"audio\": {"
                        +         "\"data\": \"" + toDataUrl(AUDIO_FILE) + "\""
                        +     "}"
                        + "}"
                        + "}";

        // URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
        String url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/audio/tts/customization";
        HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("Authorization", "Bearer " + apiKey);
        con.setRequestProperty("Content-Type", "application/json");
        con.setDoOutput(true);

        try (OutputStream os = con.getOutputStream()) {
            os.write(jsonPayload.getBytes(StandardCharsets.UTF_8));
        }

        int status = con.getResponseCode();
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(status >= 200 && status < 300 ? con.getInputStream() : con.getErrorStream(),
                        StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                response.append(line);
            }
            if (status == 200) {
                JsonObject jsonObj = new Gson().fromJson(response.toString(), JsonObject.class);
                return jsonObj.getAsJsonObject("output").get("voice").getAsString();
            }
            throw new IOException("Failed to create voice: " + status + " - " + response);
        }
    }

    public static void main(String[] args) {
        try {
            // API keys differ between Singapore and Beijing regions. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
            // If the environment variable is not configured, replace the following line with: String apiKey = "sk-xxx"
            String apiKey = System.getenv("DASHSCOPE_API_KEY");

            // 1. Voice cloning: create a custom voice
            String voice = createVoice();
            System.out.println("Voice cloning complete. Voice: " + voice);

            // 2. Non-realtime conversation with the cloned voice (OpenAI-compatible API)
            String requestBody = "{"
                    + "\"model\": \"" + TARGET_MODEL + "\","
                    + "\"messages\": [{\"role\": \"user\", \"content\": \"Hello, please introduce yourself\"}],"
                    + "\"modalities\": [\"text\", \"audio\"],"
                    + "\"audio\": {\"voice\": \"" + voice + "\", \"format\": \"wav\"},"
                    + "\"stream\": true,"
                    + "\"stream_options\": {\"include_usage\": true}"
                    + "}";

            // URL ini untuk wilayah Singapura. Masukkan ID ruang kerja Anda pada contoh. URL berbeda-beda menurut wilayah.
            String url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions";
            HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", "Bearer " + apiKey);
            con.setRequestProperty("Content-Type", "application/json");
            con.setDoOutput(true);

            try (OutputStream os = con.getOutputStream()) {
                os.write(requestBody.getBytes(StandardCharsets.UTF_8));
            }

            // 3. Parse streaming SSE response
            StringBuilder audioBase64 = new StringBuilder();
            System.out.println("Model response:");

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = br.readLine()) != null) {
                    if (!line.startsWith("data: ") || line.equals("data: [DONE]")) continue;
                    String json = line.substring(6);
                    JsonObject chunk = new Gson().fromJson(json, JsonObject.class);
                    if (!chunk.has("choices") || chunk.getAsJsonArray("choices").size() == 0) continue;

                    JsonObject delta = chunk.getAsJsonArray("choices").get(0)
                            .getAsJsonObject().getAsJsonObject("delta");
                    if (delta.has("content") && !delta.get("content").isJsonNull()) {
                        System.out.print(delta.get("content").getAsString());
                    }
                    if (delta.has("audio") && !delta.get("audio").isJsonNull()) {
                        JsonObject audio = delta.getAsJsonObject("audio");
                        if (audio.has("data")) {
                            audioBase64.append(audio.get("data").getAsString());
                        }
                    }
                }
            }

            // 4. Save audio file (API returns raw PCM data, WAV header required)
            if (audioBase64.length() > 0) {
                byte[] pcmBytes = Base64.getDecoder().decode(audioBase64.toString());
                writeWav("audio_cloned.wav", pcmBytes, 24000);
                System.out.println("\nAudio saved to: audio_cloned.wav");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Kuota suara dan pembersihan otomatis

Batas total: 1,000 suara per akun.

API ini tidak menyediakan endpoint untuk menghitung jumlah suara. Panggil API Daftar suara untuk menghitung suara Anda.

Pembersihan otomatis: Suara yang tidak digunakan selama satu tahun akan dihapus secara otomatis.

Penagihan

Kloning suara dan pemanggilan model ditagih secara terpisah:

  • Kloning suara: Buat suara dikenai biaya $0.01 per suara. Permintaan pembuatan yang gagal tidak dikenai biaya.

    CatatanKuota gratis (hanya untuk wilayah Beijing di situs Tiongkok dan wilayah Singapura di situs internasional):

    • 1,000 pembuatan suara gratis dalam 90 hari setelah mengaktifkan Model Studio.
    • Pembuatan yang gagal tidak mengurangi kuota gratis.
    • Menghapus suara tidak mengembalikan kuota gratis.
    • Setelah kuota gratis habis atau periode 90 hari berakhir, pembuatan suara dikenai biaya $0.01/suara.
  • Percakapan dengan suara kloning ditagih berdasarkan penggunaan token model. Lihat Harga inferensi model.

Hak cipta dan kepatuhan hukum

Anda bertanggung jawab atas kepemilikan dan penggunaan suara yang Anda berikan secara sah. Baca Perjanjian Layanan.

Panduan perekaman

Peralatan perekaman

Gunakan mikrofon peredam bising, atau rekam dengan ponsel dari jarak dekat di lingkungan yang tenang.

Lingkungan perekaman

Lokasi

  • Rekam di ruang kecil tertutup dengan luas 10 meter persegi atau kurang.
  • Pilih ruangan dengan material penyerap suara, seperti busa akustik, karpet, atau tirai.
  • Hindari aula terbuka yang besar, ruang rapat, atau ruang kelas dengan reverberasi tinggi.

Kontrol derau

  • Kebisingan luar: Tutup pintu dan jendela untuk menghalangi suara lalu lintas, konstruksi, dan suara lain dari luar.
  • Kebisingan dalam ruangan: Matikan AC, kipas, dan ballast lampu fluoresen.
  • Rekam suara sekitar dengan ponsel, lalu putar pada volume tinggi untuk mengidentifikasi sumber kebisingan yang tersembunyi.

Kontrol reverberasi

  • Reverberasi membuat audio terdengar teredam dan mengurangi kejelasan.
  • Kurangi pantulan dari permukaan halus: tutup tirai, buka pintu lemari pakaian, dan tutupi meja serta rak dengan pakaian atau selimut.
  • Gunakan benda berbentuk tidak beraturan, seperti rak buku dan furnitur berlapis kain, untuk menghasilkan pantulan difus.

Persiapan naskah

  • Sesuaikan naskah dengan kasus penggunaan yang dituju. Misalnya, gunakan gaya dialog layanan pelanggan untuk skenario layanan pelanggan.
  • Pastikan naskah tidak memuat konten sensitif atau ilegal, seperti materi politik, pornografi, atau kekerasan, karena hal tersebut menyebabkan kloning gagal.
  • Hindari frasa pendek (seperti "halo" atau "ya"). Gunakan kalimat lengkap.
  • Pertahankan kesinambungan makna dan hindari jeda yang sering saat membaca. Disarankan berbicara setidaknya 3 detik berturut-turut tanpa terputus.
  • Anda dapat menggunakan emosi yang diinginkan, seperti ramah atau serius. Jaga nada tetap alami dan hindari penyampaian yang berlebihan.

Langkah yang disarankan

Dengan kamar tidur biasa sebagai contoh:

  1. Tutup pintu dan jendela untuk menghalangi kebisingan dari luar.
  2. Matikan AC, kipas, dan peralatan rumah tangga lainnya.
  3. Tutup tirai untuk mengurangi pantulan dari kaca.
  4. Tutupi permukaan meja dengan pakaian atau selimut untuk mengurangi pantulan dari meja.
  5. Latih naskah, pilih nada karakter, dan bicaralah secara alami.
  6. Pertahankan jarak sekitar 10 cm dari perangkat perekaman untuk menghindari distorsi bunyi letup atau sinyal yang lemah.