跳到主要内容

语音合成 / Text-to-Speech

把文本合成为语音文件,支持流式输出。走 /v1/audio/speech 端点,OpenAI 兼容。

基础用法

from pathlib import Path
import openai

client = openai.OpenAI(
api_key="your-api-key",
base_url="https://live-turing.cn.llm.tcljd.com/api/v1",
)

speech_file = Path("hello.mp3")

response = client.audio.speech.create(
model="turing/tts-1",
voice="alloy",
input="你好,今天天气不错。",
)
response.stream_to_file(speech_file)
curl $TURING_BASE_URL/audio/speech \
-H "Authorization: Bearer $TURING_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "turing/tts-1",
"voice": "alloy",
"input": "你好,今天天气不错。"
}' \
--output hello.mp3

参数

参数作用取值
modelTTS 模型音频模型列表 为准;示例使用 turing/tts-1
voice音色OpenAI: alloy / ash / ballad / coral / echo / sage / shimmer / verse;Qwen: Cherry / Serena
input要合成的文本UTF-8 字符串
response_format输出格式mp3(默认)/ wav / flac / opus / pcm / aac
speed语速0.25 – 4.0,默认 1.0

完整 schema:/api/create-speech

音色速查

OpenAI 系(情感表达偏自然):alloyashballadcoralsageverse(推荐)/ echoshimmeralloy(备用)。

Qwen Omni 系(中文更自然):CherrySerenaEthanDylan 等(完整列表见阿里云 DashScope 文档)。


流式输出

stream_to_file 是便捷封装;底层是 chunked HTTP。想自己消费 stream:

with client.audio.speech.with_streaming_response.create(
model="turing/tts-1",
voice="alloy",
input="...",
) as resp:
with open("out.mp3", "wb") as f:
for chunk in resp.iter_bytes():
f.write(chunk)

计费

按输入字符数计费(各厂商单价见 计费与用量)。语速、格式、音色不影响单价。


常见问题

  • Qwen 音色在 OpenAI SDK 下报错model 要用 Qwen 的 TTS 模型名;音色名本身也要和模型匹配
  • 输出有杂音 → 换 response_format: "wav" 或改用 音频模型列表 中更高质量的 TTS 模型
  • 超长文本被截断 → 分段合成后拼接;单次输入建议 < 4096 字符
  • HTTPS 流断 → 客户端超时太短,加 timeout 或分段

See also