Create a Speech
Generate audio from input text. The data generated by the interface is the binary data of the audio, which requires the user to handle it themselves.
端点:POST /v1/audio/speech
支持的模型
接口支持两个 TTS 模型:
- MOSS-TTSD-v0.5:支持双角色对话脚本合成、声音克隆、长单会话语音生成,适合 AI 播客制作。
- CosyVoice2-0.5B:支持自然语言指令(如情感、语速、角色扮演、方言)、笑声/呼吸声标记。
Request Body
model (string, required)
用于语音合成的模型。
input (string, required)
待转换为音频的文本内容,长度 1 ≤ length ≤ 128000。
MOSS-TTSD-v0.5:对话脚本使用说话人标签指示轮次:[S1] 表示说话人 1、[S2] 表示说话人 2。
示例:"[S1]Hello, how are you today?[S2]I'm doing great, thanks for asking!"
CosyVoice2-0.5B:可在自然语言指令前添加 <|endofprompt|> 标记;支持 [laughter]、[breath] 等特殊标记。
示例:"Can you say it with a happy emotion? <|endofprompt|>I'm so happy, Spring Festival is coming!"
voice (string, optional)
参考音色,仅支持单一音色。如需使用脚本对话,请使用 references 字段传递两个音色。
示例:"fnlp/MOSS-TTSD-v0.5:alex"
references (array<object>, optional)
音色引用列表。voice 字段和 references 字段互斥。如需使用脚本对话,需通过 references 字段传递两个音色。仅 moss 模型支持脚本对话。
response_format (string)
音频输出格式。可选值:mp3 | opus | wav | pcm。默认 mp3。
sample_rate (number)
控制输出采样率,默认值和范围因输出格式而异:
opus:仅支持 48000 Hzwav、pcm:支持 8000、16000、24000、32000、44100 Hz,默认 44100 Hzmp3:支持 32000、44100 Hz,默认 44100 Hz
speed (number)
生成音频的速度,范围 0.25 ~ 4.0,默认 1.0。
gain (number)
音频增益(dB),范围 -10 ~ 10,默认 0.0。
stream (boolean)
是否流式输出。
代码示例
cURL
curl --location 'https://khb.net.cn/v1/audio/speech' \
--header 'Authorization: Bearer YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{
"model": "fnlp/MOSS-TTSD-v0.5",
"input": "[S1]你好,欢迎使用 KHB 算力平台。[S2]很高兴为你服务!",
"voice": "fnlp/MOSS-TTSD-v0.5:alex",
"response_format": "mp3",
"stream": false
}' \
--output output.mp3
Python
import requests
url = "https://khb.net.cn/v1/audio/speech"
payload = {
"model": "fnlp/MOSS-TTSD-v0.5",
"input": "[S1]你好,欢迎使用 KHB 算力平台。[S2]很高兴为你服务!",
"voice": "fnlp/MOSS-TTSD-v0.5:alex",
"response_format": "mp3",
"stream": True
}
headers = {
"Authorization": "Bearer YOUR_API_KEY",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers, stream=True)
if response.status_code == 200:
with open("output.mp3", "wb") as f:
for chunk in response.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
print("音频已成功保存为 output.mp3")
else:
print(f"请求失败,状态码: {response.status_code}")
print(f"错误信息: {response.text}")
Response Body
音频的二进制数据,需用户自行处理。响应头中包含 x-khb-trace-id 字段,用于追踪请求。
错误码
| 状态码 | 说明 |
|---|---|
| 200 | 成功 |
| 400 | 参数错误 |
| 401 | API Key 无效 |
| 403 | 权限不足 |
| 404 | 资源不存在 |
| 429 | 触发 Rate Limits |
| 500/503/504 | 服务端错误 |
