非即時語音合成(Qwen-TTS)API 的請求參數與返回欄位說明。
請求體 |
DashScope Python SDK中的 Copy Copy Copy
DashScope Python SDK中的 Copy Copy Copy |
modelstring(必選)模型名稱,詳情請參見支援的模型。 | |
inputobject(必選)輸入參數。
屬性 text string (必選)要合成的文本,支援多語種混合輸入。最大輸入長度為 600 個字元。voice string (必選)使用的音色,參見支援的系統音色。language_type string (可選)合成音訊語種。預設為 Auto。
|
返回對象(流式與非流式輸出格式一致) | Copy |
status_code integerHTTP狀態代碼。遵循 RFC 9110標準定義。例如:• 200:請求成功,正常返回結果• 400:用戶端請求參數錯誤• 401:未授權訪問• 404:資源未找到• 500:伺服器內部錯誤。 | |
request_id string本次請求的唯一標識,可用於問題排查。 | |
code string請求失敗時展示錯誤碼(參見錯誤碼)。 | |
message string請求失敗時展示錯誤資訊(參見錯誤碼)。 | |
outputobject模型的輸出。
屬性 text string始終為null,無需關注該參數。choicesstring始終為null,無需關注該參數。finish_reasonstring產生狀態標識:
object模型輸出的音頻資訊。
屬性 url string完整音頻檔案的 URL,有效期間 24 小時。流式輸出說明:流式模式下,API 返回多個 chunk。中間 chunk 的 audio.data 包含 Base 64 編碼的音頻片段,audio.url 為空白;最後一個 chunk 的 audio.data 為空白字串,audio.url 包含完整音頻檔案的 OSS 地址。開發人員可在最後一個 chunk 中通過 url 欄位下載完整音頻。非流式模式下,該欄位直接返回完整音頻檔案 URL。 stringBase 64 編碼的音頻資料。非流式輸出和流式輸出的中間 chunk 中返回 Base 64 編碼的音頻片段;流式輸出的最後一個 chunk 中該欄位為空白字串,音頻通過同級的 url 欄位擷取。id string音訊唯一標識。expires_at integerURL 到期時間的 UNIX 時間戳記。 | |
usage object本次請求的字元消耗資訊。
屬性 output_tokens integer輸出音訊 Token 消耗量。對於千問3-TTS-Flash模型,該欄位固定為0。input_tokens integer輸入文本的 Token 消耗量。對於千問3-TTS-Flash模型,該欄位固定為0。characters integer輸入文本的字元數。僅千問3-TTS-Flash模型返回該欄位。 | |
request_id string本次請求的 ID。 |
音訊下載與播放
執行範例前,請先取得並設定 API Key,並安裝 DashScope SDK。Python 播放範例還依賴 PyAudio 和 NumPy;PyAudio 的安裝方式請參見程式碼註解,NumPy 可透過pip install numpy 安裝。
下載音訊(Java)
需要匯入 Gson 依賴,Maven 或 Gradle 添加方式如下:- Maven
- Gradle
在
pom.xml中添加:Copy
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.1</version>
</dependency>
在
build.gradle中添加:Copy
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.13.1")
Copy
import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
public class Main {
private static final String MODEL = "qwen3-tts-flash";
public static void call() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL)
.text("Today is a wonderful day to build something people love!")
.voice(AudioParameters.Voice.CHERRY)
.parameter("language_type", "English") // 建議與文本語種一致,以獲得正確的發音和自然的語調。
.build();
MultiModalConversationResult result = conv.call(param);
String audioUrl = result.getOutput().getAudio().getUrl();
System.out.print(audioUrl);
// 下載音頻檔案到本地
try (InputStream in = new URL(audioUrl).openStream();
FileOutputStream out = new FileOutputStream("downloaded_audio.wav")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("\n音頻檔案已下載到本地:downloaded_audio.wav");
} catch (Exception e) {
System.out.println("\n下載音頻檔案時出錯:" + e.getMessage());
}
}
public static void main(String[] args) {
// 以下為新加坡地區的配置。
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
try {
call();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
串流播放
- Python
- Java
Copy
# coding=utf-8
#
# Installation instructions for pyaudio:
# APPLE Mac OS X
# brew install portaudio
# pip install pyaudio
# Debian/Ubuntu
# sudo apt-get install python-pyaudio python3-pyaudio
# or
# pip install pyaudio
# CentOS
# sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# Microsoft Windows
# python -m pip install pyaudio
import os
import dashscope
import pyaudio
import time
import base64
import numpy as np
# 以下為新加坡地區的配置。
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
p = pyaudio.PyAudio()
# 建立音頻流
stream = p.open(format=pyaudio.paInt16,
channels=1,
rate=24000,
output=True)
text = "Today is a wonderful day to build something people love!"
response = dashscope.MultiModalConversation.call(
# 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen3-tts-flash",
text=text,
voice="Cherry",
language_type="English", # 建議與文本語種一致,以獲得正確的發音和自然的語調。
stream=True
)
for chunk in response:
if chunk.output is not None:
audio = chunk.output.audio
if audio.data is not None:
wav_bytes = base64.b64decode(audio.data)
audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
# 直接播放音頻資料
stream.write(audio_np.tobytes())
if chunk.output.finish_reason == "stop":
print(f"finish at: {chunk.output.audio.expires_at}")
time.sleep(0.8)
# 清理資源
stream.stop_stream()
stream.close()
p.terminate()
需要匯入 Gson 依賴,Maven 或 Gradle 添加方式如下:
- Maven
- Gradle
在
pom.xml中添加:Copy
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.1</version>
</dependency>
在
build.gradle中添加:Copy
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.13.1")
Copy
// 請安裝 DashScope SDK 的最新版本
import com.alibaba.dashscope.aigc.multimodalconversation.AudioParameters;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import io.reactivex.Flowable;
import javax.sound.sampled.*;
import java.util.Base64;
public class Main {
private static final String MODEL = "qwen3-tts-flash";
public static void streamCall() throws ApiException, NoApiKeyException, UploadFileException {
MultiModalConversation conv = new MultiModalConversation();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// 新加坡地區和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model(MODEL)
.text("Today is a wonderful day to build something people love!")
.voice(AudioParameters.Voice.CHERRY)
.parameter("language_type", "English") // 建議與文本語種一致,以獲得正確的發音和自然的語調。
.build();
Flowable<MultiModalConversationResult> result = conv.streamCall(param);
result.blockingForEach(r -> {
try {
// 1. 擷取Base64編碼的音頻資料
String base64Data = r.getOutput().getAudio().getData();
byte[] audioBytes = Base64.getDecoder().decode(base64Data);
// 2. 配置音頻格式(根據API返回的音頻格式調整)
AudioFormat format = new AudioFormat(
AudioFormat.Encoding.PCM_SIGNED,
24000, // 採樣率(需與API返回格式一致)
16, // 採樣位元
1, // 聲道數
2, // 幀大小(位元組數)
24000, // 幀率(需與採樣率一致)
false // 大端序
);
// 3. 即時播放音頻資料
DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);
try (SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info)) {
if (line != null) {
line.open(format);
line.start();
line.write(audioBytes, 0, audioBytes.length);
line.drain();
}
}
} catch (LineUnavailableException e) {
e.printStackTrace();
}
});
}
public static void main(String[] args) {
// 以下為新加坡地區的配置。
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
try {
streamCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}