Omni voice cloning user guide
Create an Omni voice from reference audio and use it in real-time or non-real-time calls. Includes complete examples, audio requirements, quotas, and billing.
User Guide: For model introduction and selection recommendations, see Real-time (Qwen-Omni-Realtime) or Non-real-time (Qwen-Omni).
ImportantThis document is dedicated to the Qwen Omni and Qwen Omni-Realtime Voice Cloning APIs; if you are using a speech synthesis model, see the Voice Cloning User Guide.
ImportantAlibaba Cloud Model Studio has launched workspace-dedicated domains for the China (Beijing) region, which deliver superior performance and higher stability for inference requests. You are advised to migrate to the new domain:
- China (Beijing) region: migrate from
https://dashscope.aliyuncs.comtohttps://WorkspaceId.cn-beijing.maas.aliyuncs.com
Here, WorkspaceId is your workspace ID, which you can view on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains available.
For request parameters, responses, and error descriptions, see the Voice Cloning API reference.
Audio requirements
High-quality input audio is the foundation of a good cloning result.
Item | Requirement |
|---|---|
Supported formats | WAV (16bit)、MP3、M4A |
Audio Duration | Recommended 10~20 s, and no more than 60 s |
File Size | < 10 MB |
Sampling rate | ≥ 24 kHz |
Channel | Mono |
Content | The audio must contain at least 3 seconds of continuous, clear speech (no background sound); the remaining parts may only include brief pauses (≤2 seconds). The entire audio clip should be free of background music, noise, or other voices to ensure the quality of the core speech. Use normal speech audio as input, and do not upload songs or singing audio, to ensure accurate and usable cloning results |
Language | Chinese (zh), English (en), German (de), Italian (it), Portuguese (pt), Spanish (es), Japanese (ja), Korean (ko), French (fr), Russian (ru), Thai (th), Indonesian (id), Arabic (ar), Czech (cs), Danish (da), Dutch (nl), Finnish (fi), Hebrew (he), Hindi (hi), Icelandic (is), Malay (ms), Norwegian (no), Persian (fa), Polish (pl), Swedish (sv), Tagalog (tl), Turkish (tr), Urdu (ur), Vietnamese (vi) Chinese dialects: Northeastern Mandarin (Dongbei), Shaanxi dialect (Shannxi), Sichuan dialect (Sichuan), Henan dialect (Henan), Changsha dialect (Changsha), Tianjin dialect (Tianjin), Hangzhou dialect (Hangzhou), Liaoning dialect (Liaoning), Shenyang dialect (Shenyang), Anshan dialect (Anshan) |
QuickStart: Clone and use a voice
First create a voice, then call the model to use the voice:
1. Workflow
Voice cloning and model invocation are two separate but closely linked steps that follow the "create first, use later" flow:
-
Create a voice
Call the Create voice API and upload an audio clip. The system analyzes the audio and creates a dedicated cloned voice. In this step you must specify
target_model, which declares the omni-modal model that will drive the created voice.If you already have a created voice (view the voice list by calling the List voices API), you can skip this step and go directly to the next step.
-
Use the voice in a conversation
Call the Omni API (real-time or non-real-time) and pass in the voice obtained in the previous step. The omni-modal model specified in this step must be the same as the
target_modelspecified in the previous step.
2. Model Configuration and Preparations
Select an appropriate model and complete the preparations.
Model Configuration
Voice Cloning requires the following two models:
-
Voice cloning model: qwen-voice-enrollment
-
Omni-modal model that drives the voice:
- qwen3.8-omni-flash-realtime
- qwen3.5-omni-plus-realtime
- qwen3.5-omni-flash-realtime
- qwen3.5-omni-plus
- qwen3.5-omni-flash
Preparations
- Obtain an API Key: Obtain and configure an API Key. For security purposes, we recommend configuring the API Key in an environment variable.
- Fill in your Workspace ID in the example addresses below.
- Install the SDK: Make sure you have installed the latest version of the DashScope SDK.
- Prepare the audio to clone: The audio must meet the audio requirements.
3. End-to-end Examples
The following examples demonstrate how to use a dedicated voice generated through Voice Cloning in a conversation, achieving output highly similar to the original voice.
- Key principle: During Voice Cloning, the
target_model(the omni-modal model that drives the voice) must be identical to the model specified in the subsequent Omni API calls; otherwise, synthesis will fail. - The examples use a local audio file
voice.mp3for Voice Cloning. Replace it with your own file when running the code.
Real-time
Applicable to Qwen-Omni-Realtime series models. For more information, see Real-time (Qwen-Omni-Realtime).
# 依赖:dashscope >= 2.0.1,pyaudio
import os
import requests
import base64
import pathlib
import threading
import pyaudio
import dashscope
from dashscope import DashScopeError
# ======= 常量配置 =======
DEFAULT_TARGET_MODEL = "qwen3.8-omni-flash-realtime" # 声音复刻、实时对话要使用相同的模型
DEFAULT_PREFERRED_NAME = "guanyu"
DEFAULT_AUDIO_MIME_TYPE = "audio/mpeg"
VOICE_FILE_PATH = "voice.mp3" # 用于声音复刻的本地音频文件的相对路径
def create_voice(file_path: str,
url: str,
target_model: str = DEFAULT_TARGET_MODEL,
preferred_name: str = DEFAULT_PREFERRED_NAME,
audio_mime_type: str = DEFAULT_AUDIO_MIME_TYPE) -> str:
"""
创建音色,并返回 voice 参数。
当前 2.0 SDK 尚未提供 Omni 声音复刻(qwen-voice-enrollment)的管理面接口,
此处按 HTTP 原生协议直接调用创建音色接口。
"""
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为: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"音频文件不存在: {file_path}")
base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
data_uri = f"data:{audio_mime_type};base64,{base64_str}"
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"创建 voice 失败: {resp.status_code}, {resp.text}")
try:
return resp.json()["output"]["voice"]
except (KeyError, ValueError) as e:
raise RuntimeError(f"解析 voice 响应失败: {e}")
def receive_events(session, out):
"""接收线程:迭代服务端事件并按 type 分发处理,连接关闭后自然退出"""
try:
for event in session.events():
event_type = event.get("type", "")
# 音频增量:Base64 编码的 PCM 数据,解码后直接写播放流
if event_type == "response.audio.delta":
out.write(base64.b64decode(event["delta"]))
elif event_type == "conversation.item.input_audio_transcription.completed":
print(f"[User] {event.get('transcript', '')}")
elif event_type == "response.audio_transcript.done":
print(f"[LLM] {event.get('transcript', '')}")
except DashScopeError as e:
# 服务端错误事件(如参数校验失败)会以 DashScopeError 异常抛出
print(f"[Error] code={e.code}, message={e.message}, request_id={e.request_id}")
if __name__ == '__main__':
# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID;
# 如需访问新加坡地域,请将 region 替换为 ap-southeast-1。
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
base_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com"
# 1. 声音复刻:创建专属音色
voice = create_voice(VOICE_FILE_PATH, url=f"{base_url}/api/v1/services/audio/tts/customization")
print(f"声音复刻完成,音色: {voice}")
# 2. 使用复刻音色进行实时对话
pya = pyaudio.PyAudio()
out = pya.open(format=pyaudio.paInt16, channels=1, rate=24000, output=True)
mic = pya.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True)
# 进入 with 上下文自动建立连接;2.0 SDK 服务端事件不再通过回调下发,
# 改为在接收线程中迭代会话的 events() 并按 type 分发处理
with client.audio.realtime.connect(model=DEFAULT_TARGET_MODEL) as session:
# 配置会话:输出模态、使用复刻生成的专属音色、输入输出音频格式与转写
session.update_session(
["audio", "text"],
voice=voice, # 使用复刻生成的专属音色
input_audio_config={"type": "pcm", "sample_rate": 16000},
output_audio_config={"type": "pcm", "sample_rate": 24000},
enable_input_audio_transcription=True,
enable_turn_detection=True,
)
receiver = threading.Thread(target=receive_events, args=(session, out), daemon=True)
receiver.start()
print("对话已开始,对着麦克风说话 (Ctrl+C 退出)...")
try:
while True:
audio_data = mic.read(3200, exception_on_overflow=False)
# bytes 会自动 Base64 编码后发送
session.append_audio(audio_data)
except KeyboardInterrupt:
pass
finally:
# close 幂等:提前关闭连接,解除接收线程 events() 的阻塞等待
session.close()
mic.close()
out.close()
pya.terminate()
print("\n对话结束")
import com.alibaba.dashscope.audio.omni.*;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
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 {
// ===== 常量定义 =====
// 声音复刻、实时对话要使用相同的模型
private static final String TARGET_MODEL = "qwen3.8-omni-flash-realtime";
private static final String PREFERRED_NAME = "guanyu";
// 用于声音复刻的本地音频文件的相对路径
private static final String AUDIO_FILE = "voice.mp3";
private static final String AUDIO_MIME_TYPE = "audio/mpeg";
// 默认示例为华北2(北京),请填写业务空间 ID,并使用同地域的 API Key。
private static final String BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com";
// 生成 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;
}
// 调用 API 创建 voice
public static String createVoice() throws Exception {
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼API Key将下行替换为: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) + "\""
+ "}"
+ "}"
+ "}";
String url = BASE_URL + "/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("创建语音失败: " + status + " - " + response);
}
}
// 简单的音频播放器
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. 声音复刻:创建专属音色
String voice = createVoice();
System.out.println("声音复刻完成,音色: " + voice);
// 2. 使用复刻音色进行实时对话
SimpleAudioPlayer player = new SimpleAudioPlayer();
AtomicBoolean shouldStop = new AtomicBoolean(false);
OmniRealtimeParam param = OmniRealtimeParam.builder()
.model(TARGET_MODEL)
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼API Key将下行替换为:.apikey("sk-xxx")
.apikey(System.getenv("DASHSCOPE_API_KEY"))
.url(BASE_URL.replace("https://", "wss://") + "/api-ws/v1/realtime")
.build();
OmniRealtimeConversation conversation = new OmniRealtimeConversation(param, new OmniRealtimeCallback() {
@Override public void onOpen() { System.out.println("连接已建立"); }
@Override public void onClose(int code, String reason) {
System.out.println("连接已关闭 (" + 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) // 使用复刻生成的专属音色
.enableTurnDetection(true)
.enableInputAudioTranscription(true)
.build()
);
System.out.println("对话已开始,对着麦克风说话 (Ctrl+C 退出)...");
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, "正常结束");
player.close();
mic.close();
System.out.println("\n对话结束");
} catch (NoApiKeyException e) {
System.err.println("未找到API KEY: 请设置环境变量 DASHSCOPE_API_KEY");
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}
Non-real-time
Applicable to Qwen-Omni series models. For more information, see Non-real-time (Qwen-Omni).
# 依赖:dashscope >= 2.1.0,soundfile,numpy
import os
import requests
import base64
import pathlib
import numpy as np
import soundfile as sf
import dashscope
# ======= 常量配置 =======
DEFAULT_TARGET_MODEL = "qwen3.5-omni-plus" # 声音复刻、非实时对话要使用相同的模型
DEFAULT_PREFERRED_NAME = "guanyu"
DEFAULT_AUDIO_MIME_TYPE = "audio/mpeg"
VOICE_FILE_PATH = "voice.mp3" # 用于声音复刻的本地音频文件的相对路径
def create_voice(file_path: str,
url: str,
target_model: str = DEFAULT_TARGET_MODEL,
preferred_name: str = DEFAULT_PREFERRED_NAME,
audio_mime_type: str = DEFAULT_AUDIO_MIME_TYPE) -> str:
"""
创建音色,并返回 voice 参数。
当前 2.0 SDK 尚未提供 Omni 声音复刻(qwen-voice-enrollment)的管理面接口,
此处按 HTTP 原生协议直接调用创建音色接口。
"""
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为: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"音频文件不存在: {file_path}")
base64_str = base64.b64encode(file_path_obj.read_bytes()).decode()
data_uri = f"data:{audio_mime_type};base64,{base64_str}"
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"创建 voice 失败: {resp.status_code}, {resp.text}")
try:
return resp.json()["output"]["voice"]
except (KeyError, ValueError) as e:
raise RuntimeError(f"解析 voice 响应失败: {e}")
if __name__ == '__main__':
# 以下为华北2(北京)地域的配置,调用时请将 {WorkspaceId} 替换为真实的业务空间ID;
# 如需访问新加坡地域,请将 region 替换为 ap-southeast-1。
# 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
# 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
client = dashscope.Client(
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="cn-beijing",
)
base_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com"
# 1. 声音复刻:创建专属音色
voice = create_voice(VOICE_FILE_PATH, url=f"{base_url}/api/v1/services/audio/tts/customization")
print(f"声音复刻完成,音色: {voice}")
# 2. 使用复刻音色进行非实时对话
messages = [{"role": "user", "content": [{"text": "你好,请做一段自我介绍"}]}]
# modalities/audio 为签名外参数,统一通过 parameters 传入
response = client.multimodal.chat.create(
model=DEFAULT_TARGET_MODEL,
messages=messages,
stream=True,
parameters={
"modalities": ["text", "audio"],
"audio": {"voice": voice, "format": "wav"}, # 使用复刻生成的专属音色
},
)
print("模型回复:")
audio_base64_string = ""
for chunk in response:
if not chunk.choices:
continue
delta = chunk.choices[0].delta
if delta is None:
continue
# 文本增量直接打印
if delta.content:
print(delta.content, end="")
# 音频增量:从 delta.content_parts 读取 {"audio": {"data": Base64}} 形式的 part
for part in (delta.content_parts or []):
if isinstance(part, dict) and "audio" in part:
audio_base64_string += part["audio"].get("data", "")
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("\n音频文件已保存至: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 {
// ===== 常量定义 =====
// 声音复刻、非实时对话要使用相同的模型
private static final String TARGET_MODEL = "qwen3.5-omni-plus";
private static final String PREFERRED_NAME = "guanyu";
// 用于声音复刻的本地音频文件的相对路径
private static final String AUDIO_FILE = "voice.mp3";
private static final String AUDIO_MIME_TYPE = "audio/mpeg";
// 默认示例为华北2(北京),请填写业务空间 ID,并使用同地域的 API Key。
private static final String BASE_URL = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com";
// 将 PCM 数据写入标准 WAV 文件
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);
}
}
// 生成 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;
}
// 调用 API 创建 voice
public static String createVoice() throws Exception {
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼API Key将下行替换为: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) + "\""
+ "}"
+ "}"
+ "}";
String url = BASE_URL + "/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("创建语音失败: " + status + " - " + response);
}
}
public static void main(String[] args) {
try {
// 新加坡和北京地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
// 若没有配置环境变量,请用百炼API Key将下行替换为:String apiKey = "sk-xxx"
String apiKey = System.getenv("DASHSCOPE_API_KEY");
// 1. 声音复刻:创建专属音色
String voice = createVoice();
System.out.println("声音复刻完成,音色: " + voice);
// 2. 使用复刻音色进行非实时对话(OpenAI 兼容接口)
String requestBody = "{"
+ "\"model\": \"" + TARGET_MODEL + "\","
+ "\"messages\": [{\"role\": \"user\", \"content\": \"你好,请做一段自我介绍\"}],"
+ "\"modalities\": [\"text\", \"audio\"],"
+ "\"audio\": {\"voice\": \"" + voice + "\", \"format\": \"wav\"},"
+ "\"stream\": true,"
+ "\"stream_options\": {\"include_usage\": true}"
+ "}";
String url = BASE_URL + "/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. 解析流式 SSE 响应
StringBuilder audioBase64 = new StringBuilder();
System.out.println("模型回复:");
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. 保存音频文件(API 返回原始 PCM 数据,需添加 WAV 头)
if (audioBase64.length() > 0) {
byte[] pcmBytes = Base64.getDecoder().decode(audioBase64.toString());
writeWav("audio_cloned.wav", pcmBytes, 24000);
System.out.println("\n音频文件已保存至:audio_cloned.wav");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Conversational Usage
For how to use a dedicated voice generated through Voice Cloning in conversations, see QuickStart: Clone and use a voice.
Voice Quota and Automatic Cleanup Rules
-
Total limit: 1,000 voices per account
The current API does not provide a feature to query the number of voices. You can count your voices yourself by calling the Query voice list API
-
Automatic cleanup: If a voice has not been used in any model invocation request over the past year, the system will automatically delete it
Billing Details
Voice Cloning and model invocations are billed separately:
-
Voice Cloning: Create a voice is billed at 0.01 CNY per voice. Failed creations are not charged.
NoteFree quota notes (free quota is only available in the Beijing region on the China site and the Singapore region on the International site):
- Within 90 days after Alibaba Cloud Bailian is activated, you are entitled to 1,000 free voice creation attempts.
- Failed creations do not consume free attempts.
- Deleting a voice does not restore free attempts.
- After the free quota is used up or the 90-day validity period expires, creating a voice will be billed at 0.01 CNY per voice.
-
Conversation with a cloned voice: Billed by token usage for model invocation. For details, see Model inference pricing.
Copyright and Legality
You are responsible for the ownership and legal use of the voice you provide. Read the Service Agreement.
Recording Guidelines
Recording Equipment
Use a noise-cancelling microphone, or record with a phone at close range in a quiet environment.
Recording Environment
Venue
- Record in a small enclosed space of 10 square meters or less.
- Choose a room with sound-absorbing materials such as acoustic foam, carpets, or curtains.
- Avoid large open halls, conference rooms, or classrooms where reverberation is high.
Noise Control
- Outdoor noise: Close doors and windows to block traffic, construction, and other external sounds.
- Indoor noise: Turn off air conditioners, fans, and fluorescent light ballasts.
- Record ambient sound with your phone and play it back at high volume to identify hidden noise sources.
Reverb Control
- Reverberation causes audio to sound muffled and reduces clarity.
- Reduce reflections from smooth surfaces: close curtains, open wardrobe doors, and cover desks and shelves with clothing or blankets.
- Use irregular objects such as bookshelves and upholstered furniture to create diffuse reflections.
Recording Script
- Match the script to the target use case. For example, use customer service dialog style for a customer service scenario.
- Make sure the script doesn't contain sensitive or illegal content (such as political, pornographic, or violent material), as this causes cloning to fail.
- Avoid short phrases (such as "hello" or "yes"). Use complete sentences.
- Maintain semantic coherence and avoid frequent pauses when reading. At least 3 consecutive seconds without interruption is recommended.
- You can convey the target emotion (such as friendly or serious), but avoid overly dramatic or theatrical delivery. Keep the tone natural.
Operation Recommendations
Using a typical bedroom as an example:
- Close doors and windows to block external noise.
- Turn off air conditioners, fans, and other appliances.
- Close curtains to reduce glass reflections.
- Cover the desk surface with clothing or a blanket to reduce desktop reflections.
- Familiarize yourself with the script, set the character's tone, and deliver naturally.
- Maintain about 10 cm distance from the recording device to avoid plosive distortion or weak signal.
Error messages
For troubleshooting, see Error codes.