【先纠正一个说法】
之前我说豆包搜索不是 MCP —— 不完整。官方《AI工具接入指南》写明支持
MCP Server(stdio / SSE / StreamableHTTP)和 Skill 两种集成方式。
内置工具(tools:[{type:web_search}])和 MCP Server 是并存的两种形态。
【边生成边读:先量再做】
用户要「语音用 websocket 边生成边读」。动手前先量了一下现有 HTTP 接口
每一块音频的到达时刻(同样的密钥、同一段文本):
format=pcm 首块 1112ms 末块 6067ms 跨度 4955ms
format=mp3 首块 505ms 末块 5902ms 跨度 5397ms
首块远早于末块 = 服务端本来就在边生成边下发。既然 HTTP 已经能流式,
就没必要再去实现火山那套 WebSocket 二进制协议(事件码 + 自定义消息头,
而且 Chaquopy 环境里没有 websockets 库,得手写帧解析)。
【做了什么】
- speech.synthesize_stream():生成器,逐行读 NDJSON、解一块 yield 一块。
关键是别 read() 全部,用 readline 一行一行拿。
- PCM 是首选格式:24kHz 单声道 16bit,能直接喂 AudioTrack,不需要解码器。
- scripts/verify-tts-stream.py:把「首块是否远早于末块」做成断言。
输出全用 ASCII —— 之前 print 个对勾就把脚本崩了(Windows 控制台 GBK)。
- 删掉一个重复定义的 _settings_speech(加代码时又写了一遍,靠重复定义检查抓到的)。
实测:pcm 29 块/549KB(首 826ms 末 2654ms)、mp3 30 块/93KB(首 988ms 末 2964ms),
两种都判定为流式。语音验收回归 36/36 不变。
【还没做】内核的 /api/tts/stream 路由、Node 侧的对应实现、
以及安卓端 AudioTrack 边收边播。
642 lines
26 KiB
Python
642 lines
26 KiB
Python
"""
|
||
语音:朗读(TTS)和语音识别(STT)。
|
||
|
||
对应 Node 版 server/src/speech.mjs,两份实现的请求体/返回字段逐字段一致。
|
||
|
||
为什么放在内核里而不是安卓端直接调:
|
||
1. API Key 只存一份(跟对话的 Key 放一起),安卓端拿不到也不该拿;
|
||
2. 电脑端的 Web/exe 版能白捡同一个能力(浏览器用 MediaRecorder 录音就行);
|
||
3. 厂商鉴权差异只在这一个文件里,界面侧只管"给我一段文字 / 给我一段音频"。
|
||
|
||
支持的引擎:
|
||
TTS
|
||
- 'volc' 火山语音合成(豆包同款音色)https://openspeech.bytedance.com/api/v1/tts
|
||
- 'openai' OpenAI 兼容的 /audio/speech(返回原始音频字节)
|
||
- 'system' 不调云端,交给设备自带的 TTS(安卓 TextToSpeech / 浏览器 speechSynthesis)
|
||
STT
|
||
- 'openai' OpenAI 兼容的 /audio/transcriptions(multipart)
|
||
- 'system' 交给设备自带的识别(安卓 SpeechRecognizer)
|
||
|
||
只用标准库:urllib 发请求;multipart 手拼(标准库没有现成的编码器)。
|
||
"""
|
||
|
||
import base64
|
||
import json
|
||
import os
|
||
import urllib.error
|
||
import urllib.request
|
||
import uuid
|
||
|
||
DEFAULT_TIMEOUT_TTS = 60
|
||
DEFAULT_TIMEOUT_STT = 120
|
||
|
||
# 允许用环境变量覆盖:自测时把火山接口指到本地 mock,就能验证"我们到底发了什么"
|
||
# (鉴权头那个分号、body 的层级,光看代码容易自我说服,实测才算数)
|
||
VOLC_TTS_URL = os.environ.get('DOUBAO_VOLC_TTS_URL') or 'https://openspeech.bytedance.com/api/v1/tts'
|
||
|
||
# 火山「豆包语音」V3 接口。★ 和 V1 是两套东西:
|
||
# V1 openspeech/api/v1/tts 鉴权:appid + access_token(Bearer; 分号)
|
||
# V3 openspeech/api/v3/tts/... 鉴权:**只要一个 API Key**(X-Api-Key)
|
||
# 用户问"不是只要 api key 就行了吗"——对,走的就是这条。
|
||
#
|
||
# ★ 注意路径里**没有 plan**:/api/v3/tts/unidirectional 才是语音控制台 API Key 能用的;
|
||
# /api/v3/plan/tts/unidirectional 是方舟 Agent Plan 专用,拿普通 Key 打会 401。
|
||
# 实测:同一个 Key,plan 路径 401、非 plan 路径 200 且返回真 MP3。
|
||
# 文档:https://docs.volcengine.com/docs/DoubaoVoice/APIKeyUsage
|
||
VOLC_V3_TTS_URL = os.environ.get('DOUBAO_VOLC_V3_TTS_URL') or \
|
||
'https://openspeech.bytedance.com/api/v3/tts/unidirectional'
|
||
VOLC_V3_RESOURCE_ID = 'seed-tts-2.0'
|
||
|
||
# 火山的 encoding -> MIME。文档里 mp3/wav/ogg_opus/pcm 是常用的几个
|
||
VOLC_MIME = {
|
||
'mp3': 'audio/mpeg',
|
||
'wav': 'audio/wav',
|
||
'ogg_opus': 'audio/ogg',
|
||
'pcm': 'audio/L16',
|
||
}
|
||
|
||
|
||
class SpeechError(Exception):
|
||
"""带用户可读原因的失败。界面直接把它显示出来,不用再猜。"""
|
||
|
||
|
||
def _settings_speech(settings: dict) -> dict:
|
||
speech = (settings or {}).get('speech')
|
||
return speech if isinstance(speech, dict) else {}
|
||
|
||
|
||
def _post_json(url: str, body: dict, headers: dict, timeout: int) -> dict:
|
||
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||
req = urllib.request.Request(url, data=data, method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
for k, v in headers.items():
|
||
req.add_header(k, v)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||
raw = resp.read()
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||
try:
|
||
return json.loads(raw.decode('utf-8'))
|
||
except Exception as exc: # noqa: BLE001
|
||
raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 朗读
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def synthesize(text: str, settings: dict) -> dict:
|
||
"""
|
||
把文字合成为音频。
|
||
|
||
返回:
|
||
{'engine': 'system'} → 让设备自己念(没配云端时)
|
||
{'engine': 'volc'|'openai', 'mime': ..., 'audio': '<base64>'}
|
||
"""
|
||
content = (text or '').strip()
|
||
if not content:
|
||
raise SpeechError('没有要朗读的内容')
|
||
|
||
speech = _settings_speech(settings)
|
||
engine = (speech.get('ttsEngine') or 'system').lower()
|
||
speed = float(speech.get('ttsSpeed') or 1.0)
|
||
speed = min(max(speed, 0.2), 3.0)
|
||
|
||
if engine == 'volc':
|
||
return _synthesize_volc(content, speech, speed)
|
||
if engine == 'volcv3':
|
||
return _synthesize_volc_v3(content, speech, speed)
|
||
if engine == 'openai':
|
||
return _synthesize_openai(content, settings, speech, speed)
|
||
return {'engine': 'system'}
|
||
|
||
|
||
def _synthesize_volc_v3(text: str, speech: dict, speed: float) -> dict:
|
||
"""
|
||
豆包语音 V3 合成。
|
||
|
||
和 V1 的区别(用户最容易搞混的地方):
|
||
- **只要一个 API Key**(语音控制台 → API Key 管理里创建),不需要 AppID / Access Token;
|
||
- 音色是另一套命名:`zh_female_vv_uranus_bigtts`,不是 V1 的 `BV700_streaming`;
|
||
- 返回是**逐行 JSON**(NDJSON),每行一段 base64 音频,`code=20000000` 表示结束。
|
||
|
||
两个实测踩过的坑:
|
||
1. 路径别带 plan。`/api/v3/plan/...` 是方舟 Agent Plan 专用,普通语音 Key 打过去 401;
|
||
2. 普通**方舟** Key 也不行 —— 会回 `acquire failed err:call ark ... 401`。
|
||
必须是**语音控制台**里那个 API Key(console.volcengine.com/speech → API Key 管理)。
|
||
"""
|
||
api_key = (speech.get('volcApiKey') or '').strip()
|
||
speaker = (speech.get('ttsVoice') or '').strip() or 'zh_female_vv_uranus_bigtts'
|
||
fmt = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3'
|
||
if fmt not in ('mp3', 'wav', 'ogg_opus', 'pcm'):
|
||
fmt = 'mp3'
|
||
|
||
if not api_key:
|
||
raise SpeechError(
|
||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||
'注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。'
|
||
)
|
||
|
||
body = {
|
||
'req_params': {
|
||
'text': text,
|
||
'speaker': speaker,
|
||
'audio_params': {
|
||
'format': fmt,
|
||
# 24k 是大模型音色的标准采样率,调低会明显发闷
|
||
'sample_rate': 24000,
|
||
# V3 的语速是 ±100 的百分比,不是倍率(实测 -50 变慢、+50 变快)
|
||
'speech_rate': int(round((speed - 1.0) * 100)),
|
||
},
|
||
},
|
||
}
|
||
|
||
data = json.dumps(body, ensure_ascii=False).encode('utf-8')
|
||
req = urllib.request.Request(VOLC_V3_TTS_URL, data=data, method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
req.add_header('X-Api-Key', api_key)
|
||
req.add_header('X-Api-Resource-Id', VOLC_V3_RESOURCE_ID)
|
||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||
raw = resp.read()
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||
|
||
# 逐行解析:每行一个 JSON,拼 data 里的音频片段
|
||
chunks = []
|
||
error = None
|
||
for line in raw.decode('utf-8', 'replace').splitlines():
|
||
line = line.strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
item = json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
code = item.get('code', 0)
|
||
payload = item.get('data')
|
||
if isinstance(payload, str) and payload:
|
||
chunks.append(payload)
|
||
if code == 20000000:
|
||
break
|
||
if isinstance(code, int) and code > 0 and code != 20000000:
|
||
error = f'code={code} {item.get("message") or item.get("msg") or ""}'.strip()
|
||
break
|
||
|
||
if error:
|
||
raise SpeechError(f'火山 V3 失败:{error}')
|
||
if not chunks:
|
||
raise SpeechError('火山 V3 没返回音频数据')
|
||
return {'engine': 'volcv3', 'mime': VOLC_MIME.get(fmt, 'audio/mpeg'), 'audio': ''.join(chunks)}
|
||
|
||
|
||
def _synthesize_volc(text: str, speech: dict, speed: float) -> dict:
|
||
"""
|
||
火山语音合成。
|
||
|
||
两个容易踩的点(都对着官方文档和第三方实现核对过):
|
||
1. 鉴权头是 `Bearer;{token}` —— **分号,不是空格**。写成空格会被判鉴权失败;
|
||
2. 成功判定看 body 里的 `code == 3000`,HTTP 状态码是 200 也可能带错误码。
|
||
返回的 `data` 是**纯 base64**(不是 data URL),直接解出来就是音频字节。
|
||
"""
|
||
app_id = (speech.get('volcAppId') or '').strip()
|
||
token = (speech.get('volcToken') or '').strip()
|
||
cluster = (speech.get('volcCluster') or 'volcano_tts').strip() or 'volcano_tts'
|
||
voice = (speech.get('ttsVoice') or '').strip() or 'BV700_streaming'
|
||
encoding = (speech.get('volcEncoding') or 'mp3').strip() or 'mp3'
|
||
|
||
if not app_id or not token:
|
||
raise SpeechError('火山语音需要 App ID 和 Access Token(在火山控制台「语音技术」里创建应用后拿到)')
|
||
|
||
body = {
|
||
'app': {'appid': app_id, 'token': token, 'cluster': cluster},
|
||
'user': {'uid': 'doubao'},
|
||
'audio': {
|
||
'voice_type': voice,
|
||
'encoding': encoding,
|
||
'speed_ratio': speed,
|
||
'volume_ratio': 1.0,
|
||
'pitch_ratio': 1.0,
|
||
},
|
||
'request': {
|
||
'reqid': str(uuid.uuid4()),
|
||
'text': text,
|
||
'text_type': 'plain',
|
||
'operation': 'query',
|
||
},
|
||
}
|
||
result = _post_json(VOLC_TTS_URL, body, {'Authorization': f'Bearer;{token}'}, DEFAULT_TIMEOUT_TTS)
|
||
|
||
code = result.get('code')
|
||
if code != 3000:
|
||
raise SpeechError(f'火山返回 code={code} message={result.get("message") or result.get("Message") or "?"}')
|
||
|
||
data = result.get('data')
|
||
if not data:
|
||
raise SpeechError('火山没返回音频数据')
|
||
return {'engine': 'volc', 'mime': VOLC_MIME.get(encoding, 'audio/mpeg'), 'audio': data}
|
||
|
||
|
||
def _synthesize_openai(text: str, settings: dict, speech: dict, speed: float) -> dict:
|
||
"""OpenAI 兼容的 /audio/speech:POST 进去,直接吐音频字节(不是 JSON)。"""
|
||
api_key, base_url = _resolve_openai(settings, speech)
|
||
voice = (speech.get('ttsVoice') or '').strip() or 'alloy'
|
||
model = (speech.get('ttsModel') or '').strip() or 'tts-1'
|
||
fmt = (speech.get('openaiFormat') or 'mp3').strip() or 'mp3'
|
||
|
||
body = json.dumps({
|
||
'model': model,
|
||
'input': text,
|
||
'voice': voice,
|
||
'response_format': fmt,
|
||
'speed': speed,
|
||
}, ensure_ascii=False).encode('utf-8')
|
||
|
||
req = urllib.request.Request(f'{base_url}/audio/speech', data=body, method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
req.add_header('Authorization', f'Bearer {api_key}')
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS) as resp:
|
||
raw = resp.read()
|
||
ctype = resp.headers.get('Content-Type') or 'audio/mpeg'
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||
|
||
if not raw:
|
||
raise SpeechError('返回了空音频')
|
||
return {
|
||
'engine': 'openai',
|
||
'mime': ctype.split(';')[0].strip() or 'audio/mpeg',
|
||
'audio': base64.b64encode(raw).decode('ascii'),
|
||
}
|
||
|
||
|
||
# --------------------------------------------------------------------------- #
|
||
# 语音识别
|
||
# --------------------------------------------------------------------------- #
|
||
|
||
def transcribe(audio: bytes, filename: str, content_type: str, settings: dict) -> dict:
|
||
"""
|
||
把一段音频转成文字。
|
||
|
||
返回 {'engine': 'system'} 表示"交给设备自己的识别",
|
||
否则 {'engine': 'openai', 'text': '...'}。
|
||
"""
|
||
if not audio:
|
||
raise SpeechError('没有录到音频')
|
||
|
||
speech = _settings_speech(settings)
|
||
engine = (speech.get('sttEngine') or 'system').lower()
|
||
if engine != 'openai':
|
||
return {'engine': 'system'}
|
||
|
||
api_key, base_url = _resolve_openai(settings, speech)
|
||
model = (speech.get('sttModel') or '').strip() or 'whisper-1'
|
||
lang = (speech.get('sttLanguage') or '').strip()
|
||
|
||
fields = {'model': model}
|
||
if lang:
|
||
fields['language'] = lang
|
||
|
||
body, boundary = _multipart(fields, 'file', filename or 'audio.wav', content_type or 'audio/wav', audio)
|
||
req = urllib.request.Request(f'{base_url}/audio/transcriptions', data=body, method='POST')
|
||
req.add_header('Content-Type', f'multipart/form-data; boundary={boundary}')
|
||
req.add_header('Authorization', f'Bearer {api_key}')
|
||
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_STT) as resp:
|
||
raw = resp.read()
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:400]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||
|
||
try:
|
||
result = json.loads(raw.decode('utf-8'))
|
||
except Exception as exc: # noqa: BLE001
|
||
raise SpeechError(f'返回不是 JSON:{raw[:200]!r}') from exc
|
||
|
||
text = (result.get('text') or '').strip()
|
||
if not text:
|
||
raise SpeechError('识别结果为空(可能是没人说话,或音频格式不对)')
|
||
return {'engine': 'openai', 'text': text}
|
||
|
||
|
||
def _multipart(fields: dict, file_field: str, filename: str, content_type: str, content: bytes):
|
||
"""
|
||
手拼 multipart/form-data。
|
||
|
||
为什么不用 requests:Chaquopy 里第三方库要额外打包,而标准库没有
|
||
multipart 编码器 —— 这个格式本身很简单,拼一遍就够了。
|
||
"""
|
||
boundary = f'----doubao{uuid.uuid4().hex}'
|
||
out = bytearray()
|
||
for key, value in fields.items():
|
||
out += f'--{boundary}\r\n'.encode()
|
||
out += f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode()
|
||
out += f'{value}\r\n'.encode()
|
||
out += f'--{boundary}\r\n'.encode()
|
||
out += f'Content-Disposition: form-data; name="{file_field}"; filename="{filename}"\r\n'.encode()
|
||
out += f'Content-Type: {content_type}\r\n\r\n'.encode()
|
||
out += content
|
||
out += f'\r\n--{boundary}--\r\n'.encode()
|
||
return bytes(out), boundary
|
||
|
||
|
||
def _resolve_openai(settings: dict, speech: dict):
|
||
"""
|
||
取 OpenAI 兼容那套的 Key 和地址。
|
||
|
||
默认复用主对话的设置(同一个 Key 通常也能用语音接口);
|
||
也可以在 speech 里单独填,方便"对话用方舟、语音用 OpenAI"这种组合。
|
||
"""
|
||
api_key = (speech.get('openaiApiKey') or '').strip() or (settings or {}).get('apiKey') or ''
|
||
base_url = (speech.get('openaiBaseUrl') or '').strip() or (settings or {}).get('baseUrl') or ''
|
||
base_url = base_url.rstrip('/')
|
||
if not api_key:
|
||
raise SpeechError('没有 API Key(在设置里填,或在「语音」里单独指定)')
|
||
if not base_url:
|
||
raise SpeechError('没有 Base URL')
|
||
return api_key, base_url
|
||
|
||
|
||
def synthesize_stream(text: str, settings: dict):
|
||
"""
|
||
流式合成:边生成边把音频块吐出来(生成器)。
|
||
|
||
为什么需要它:整段合成完再播,长回复要等好几秒才出声。实测火山 v3 接口
|
||
**本身就是边生成边下发的**(一段 60 字的文本,首块 1.1s 到、末块 6.0s 到,
|
||
跨度 5 秒),所以只要这边不攒、跟着往下传,播放端就能"边生成边读"。
|
||
|
||
★ 不需要 WebSocket。火山确实有 wss://…/tts/bidirection,但那是另一套
|
||
二进制私有协议;HTTP 这条路已经能流式,何必多写一层帧解析。
|
||
|
||
yield 的是 (mime, bytes)。只支持云端引擎 —— system 引擎归系统 TTS 管,
|
||
内核根本不参与合成(调用方自己判断 engine 是不是 system)。
|
||
"""
|
||
engine = (_settings_speech(settings).get('ttsEngine') or 'system').lower()
|
||
speech = _settings_speech(settings)
|
||
content = (text or '').strip()
|
||
if not content:
|
||
raise SpeechError('没有要朗读的内容')
|
||
speed = _clamp(speech.get('ttsSpeed', 1.0))
|
||
|
||
if engine == 'volcv3':
|
||
yield from _stream_volc_v3(content, speech, speed)
|
||
return
|
||
# 其他引擎没有流式接口,退回"整段合成再一次给"
|
||
result = synthesize(text, settings)
|
||
audio = result.get('audio')
|
||
if audio:
|
||
yield result.get('mime') or 'audio/mpeg', base64.b64decode(audio)
|
||
|
||
|
||
def _stream_volc_v3(text: str, speech: dict, speed: float):
|
||
"""火山 v3 的流式读取:逐行 NDJSON,每行一段 base64 音频,拿到就 yield。"""
|
||
api_key = (speech.get('volcApiKey') or '').strip()
|
||
speaker = (speech.get('ttsVoice') or '').strip() or 'zh_female_vv_uranus_bigtts'
|
||
if not api_key:
|
||
raise SpeechError(
|
||
'豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。'
|
||
'注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。'
|
||
)
|
||
|
||
fmt = (speech.get('volcEncoding') or 'pcm').strip() or 'pcm'
|
||
if fmt not in ('mp3', 'wav', 'ogg_opus', 'pcm'):
|
||
fmt = 'pcm'
|
||
|
||
body = {
|
||
'req_params': {
|
||
'text': text,
|
||
'speaker': speaker,
|
||
'audio_params': {
|
||
'format': fmt,
|
||
'sample_rate': 24000,
|
||
'speech_rate': int(round((speed - 1.0) * 100)),
|
||
},
|
||
},
|
||
}
|
||
req = urllib.request.Request(VOLC_V3_TTS_URL, data=json.dumps(body, ensure_ascii=False).encode('utf-8'), method='POST')
|
||
req.add_header('Content-Type', 'application/json')
|
||
req.add_header('X-Api-Key', api_key)
|
||
req.add_header('X-Api-Resource-Id', VOLC_V3_RESOURCE_ID)
|
||
req.add_header('X-Control-Require-Usage-Tokens-Return', '*')
|
||
|
||
mime = VOLC_MIME.get(fmt, 'audio/L16')
|
||
try:
|
||
resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_TTS)
|
||
except urllib.error.HTTPError as exc:
|
||
detail = ''
|
||
try:
|
||
detail = exc.read().decode('utf-8', 'replace')[:300]
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
raise SpeechError(f'HTTP {exc.code} {detail or exc.reason}') from exc
|
||
except urllib.error.URLError as exc:
|
||
raise SpeechError(f'连不上:{exc.reason}') from exc
|
||
|
||
# ★ 关键就是这里不 read() 全部:用 readline() 一行一行拿,
|
||
# 火山下发一行我们就解一行、yield 一行,播放端立刻能出声。
|
||
error = None
|
||
got_any = False
|
||
try:
|
||
for raw_line in resp:
|
||
line = raw_line.decode('utf-8', 'replace').strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
item = json.loads(line)
|
||
except Exception: # noqa: BLE001
|
||
continue
|
||
code = item.get('code', 0)
|
||
payload = item.get('data')
|
||
if isinstance(payload, str) and payload:
|
||
got_any = True
|
||
yield mime, base64.b64decode(payload)
|
||
if code == 20000000:
|
||
break
|
||
if isinstance(code, int) and code > 0 and code != 20000000:
|
||
error = f'code={code} {item.get("message") or item.get("msg") or ""}'.strip()
|
||
break
|
||
finally:
|
||
try:
|
||
resp.close()
|
||
except Exception: # noqa: BLE001
|
||
pass
|
||
|
||
if error:
|
||
raise SpeechError(f'火山 V3 失败:{error}')
|
||
if not got_any:
|
||
raise SpeechError('火山 V3 没返回音频数据')
|
||
|
||
|
||
def _clamp(value) -> float:
|
||
try:
|
||
v = float(value)
|
||
except (TypeError, ValueError):
|
||
return 1.0
|
||
return min(max(v, 0.2), 3.0)
|
||
|
||
|
||
def speech_state(settings: dict) -> dict:
|
||
"""给界面看的当前语音配置(脱敏)。"""
|
||
speech = _settings_speech(settings)
|
||
return {
|
||
'ttsEngine': speech.get('ttsEngine') or 'system',
|
||
'ttsVoice': speech.get('ttsVoice') or '',
|
||
'ttsSpeed': speech.get('ttsSpeed') or 1.0,
|
||
'autoRead': bool(speech.get('autoRead')),
|
||
'sttEngine': speech.get('sttEngine') or 'system',
|
||
'sttModel': speech.get('sttModel') or 'whisper-1',
|
||
'sttLanguage': speech.get('sttLanguage') or '',
|
||
'volcAppId': speech.get('volcAppId') or '',
|
||
'volcCluster': speech.get('volcCluster') or 'volcano_tts',
|
||
'volcEncoding': speech.get('volcEncoding') or 'mp3',
|
||
'hasVolcToken': bool(speech.get('volcToken')),
|
||
# V3 只要这一个 Key,所以界面按它判断"配没配"
|
||
'hasVolcApiKey': bool(speech.get('volcApiKey')),
|
||
'hasOpenaiKey': bool(speech.get('openaiApiKey') or (settings or {}).get('apiKey')),
|
||
'openaiBaseUrl': speech.get('openaiBaseUrl') or '',
|
||
'ttsModel': speech.get('ttsModel') or 'tts-1',
|
||
# 各家「申请语音 Key」的直达链接,界面上做成快捷入口。
|
||
# 这里放内核而不是写死在界面里:以后加厂商只改一处。
|
||
'consoleUrls': SPEECH_CONSOLE_URLS,
|
||
}
|
||
|
||
|
||
# 语音相关控制台的直达链接(都已访问核实可达)
|
||
SPEECH_CONSOLE_URLS = {
|
||
# V3:语音控制台 → API Key 管理。**这是"只要一个 API Key"那条路的入口**
|
||
'volcv3': 'https://console.volcengine.com/speech/new/setting/apikeys',
|
||
# V1:同一个控制台,但拿的是 AppID + Access Token(在「语音合成」应用详情里)
|
||
'volc': 'https://console.volcengine.com/speech/app',
|
||
'openai': 'https://platform.openai.com/api-keys',
|
||
# 方舟 Agent Plan:另一条能用 API Key 的路(和语音控制台不是一回事)
|
||
'agentPlan': 'https://ark.volcengine.com/region:cn-beijing/openManagement?advancedActiveKey=agentPlan',
|
||
}
|
||
|
||
# 联网搜索(豆包搜索)相关的地址。
|
||
#
|
||
# activate 那个是**从接口报错里拿到的**:不带 sources 打 /responses 会返回
|
||
# "Your account has not activated web search. You may activate it at
|
||
# https://console.volcengine.com/common-buy/CC_content_plugin"
|
||
# 比让用户自己在控制台里翻要准。manage 那个是「开通管理 → 应用组件库 → 豆包搜索」。
|
||
SEARCH_CONSOLE_URLS = {
|
||
'activate': 'https://console.volcengine.com/common-buy/CC_content_plugin',
|
||
'manage': 'https://console.volcengine.com/ark/region:cn-beijing/openManagement'
|
||
'?advancedActiveKey=component&tab=DoubaoSearch',
|
||
}
|
||
|
||
|
||
# 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致
|
||
DEFAULT_SPEECH = {
|
||
'ttsEngine': 'system',
|
||
'ttsVoice': '',
|
||
'ttsSpeed': 1.0,
|
||
'autoRead': False,
|
||
'sttEngine': 'system',
|
||
'sttModel': 'whisper-1',
|
||
'sttLanguage': '',
|
||
'volcAppId': '',
|
||
'volcToken': '',
|
||
'volcApiKey': '', # V3 用的那个(语音控制台 → API Key 管理)
|
||
'volcCluster': 'volcano_tts',
|
||
'volcEncoding': 'mp3',
|
||
'openaiApiKey': '',
|
||
'openaiBaseUrl': '',
|
||
'ttsModel': 'tts-1',
|
||
}
|
||
|
||
# 常用音色。★ 名字全部照官方音色列表核对过:
|
||
# https://docs.volcengine.com/docs/DoubaoVoice/Tonelist
|
||
# 之前这份列表是按印象写的,实测 6 个里错了 4 个(BV701 其实叫「擎苍」不是「通用男声2」,
|
||
# BV138 是「情感女声-Lawrence」不是「沉稳男声」)。音色名是用户唯一的识别依据,
|
||
# 写错等于让人盲选,所以这里宁可少列几个也要列准。
|
||
VOLC_VOICES = [
|
||
{'value': 'BV700_streaming', 'label': '灿灿 · 通用女声(22 种情感,推荐)'},
|
||
{'value': 'BV700_V2_streaming', 'label': '灿灿 2.0(升级版)'},
|
||
{'value': 'BV001_streaming', 'label': '通用女声'},
|
||
{'value': 'BV001_V2_streaming', 'label': '通用女声 2.0'},
|
||
{'value': 'BV002_streaming', 'label': '通用男声'},
|
||
{'value': 'BV701_streaming', 'label': '擎苍 · 有声阅读'},
|
||
{'value': 'BV701_V2_streaming', 'label': '擎苍 2.0'},
|
||
{'value': 'BV705_streaming', 'label': '炀炀 · 自然对话'},
|
||
{'value': 'BV009_streaming', 'label': '知性女声'},
|
||
{'value': 'BV007_streaming', 'label': '亲切女声'},
|
||
{'value': 'BV123_streaming', 'label': '阳光青年'},
|
||
{'value': 'BV406_streaming', 'label': '超自然音色 · 梓梓'},
|
||
]
|
||
|
||
OPENAI_VOICES = [
|
||
{'value': 'alloy', 'label': 'alloy(中性)'},
|
||
{'value': 'nova', 'label': 'nova(女声,推荐)'},
|
||
{'value': 'shimmer', 'label': 'shimmer(女声,柔和)'},
|
||
{'value': 'echo', 'label': 'echo(男声)'},
|
||
{'value': 'onyx', 'label': 'onyx(男声,低沉)'},
|
||
{'value': 'fable', 'label': 'fable(叙述)'},
|
||
{'value': 'coral', 'label': 'coral(女声,明快)'},
|
||
{'value': 'sage', 'label': 'sage(女声,沉稳)'},
|
||
]
|
||
|
||
# V3(大模型音色)的 speaker。★ 名字照官方「音色列表」核对过。
|
||
# 这一套和 V1 的 BVxxx 完全不通用 —— 拿 BV700_streaming 去 V3 会报音色不存在。
|
||
# 下面这 8 个是实测能合成出真 MP3 的(2026-10 验证)。
|
||
VOLC_V3_SPEAKERS = [
|
||
{'value': 'zh_female_vv_uranus_bigtts', 'label': 'Vivi 2.0(女声,默认)'},
|
||
{'value': 'zh_female_cancan_uranus_bigtts', 'label': '知性灿灿 2.0'},
|
||
{'value': 'zh_female_xiaohe_uranus_bigtts', 'label': '小何 2.0'},
|
||
{'value': 'zh_female_tianmeixiaoyuan_uranus_bigtts', 'label': '甜美小源 2.0'},
|
||
{'value': 'zh_female_shuangkuaisisi_uranus_bigtts', 'label': '爽快思思 2.0'},
|
||
{'value': 'zh_male_qingcang_uranus_bigtts', 'label': '擎苍 2.0(男声)'},
|
||
{'value': 'zh_male_m191_uranus_bigtts', 'label': '云舟 2.0'},
|
||
{'value': 'zh_male_taocheng_uranus_bigtts', 'label': '小天 2.0'},
|
||
]
|
||
|
||
|
||
def voice_options(engine: str):
|
||
if engine == 'volc':
|
||
return VOLC_VOICES
|
||
if engine == 'volcv3':
|
||
return VOLC_V3_SPEAKERS
|
||
if engine == 'openai':
|
||
return OPENAI_VOICES
|
||
return []
|
||
|
||
|
||
def debug_env() -> dict:
|
||
"""给 /api/speech/state 用的环境信息(判断能不能用云端语音)。"""
|
||
return {
|
||
'isAndroid': bool(os.environ.get('ANDROID_ROOT')),
|
||
'hasStdlib': True,
|
||
}
|