边生成边读:实测 HTTP 接口就是流式的,不用 WebSocket

【先纠正一个说法】
之前我说豆包搜索不是 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 边收边播。
This commit is contained in:
l
2026-10-09 17:44:35 +08:00
parent e288ced3fc
commit a85a8858bf
2 changed files with 179 additions and 0 deletions

View File

@@ -390,6 +390,124 @@ def _resolve_openai(settings: dict, speech: dict):
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)

View File

@@ -0,0 +1,61 @@
"""实测 Python 内核的流式合成:首块多久到、一共几块。
跑法: VOLC_KEY=xxx python scripts/verify-tts-stream.py
注意:输出全部用 ASCII。Windows 控制台默认 GBK,print 个 ✓ 就能让整个脚本崩掉
(真崩过),验收脚本不能因为这种原因失败。
"""
import os
import sys
import time
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'android', 'kernel'))
import speech # noqa: E402
key = os.environ.get('VOLC_KEY', '').strip()
if not key:
print(' 需要 VOLC_KEY 环境变量')
sys.exit(2)
TEXT = ('人工智能正在改变我们生活的方方面面。从早上叫醒我们的智能音箱,'
'到通勤路上推荐路线的导航软件,再到工作中帮我们整理资料的助手。')
failed = 0
for encoding in ('pcm', 'mp3'):
settings = {
'speech': {
'ttsEngine': 'volcv3',
'volcApiKey': key,
'ttsVoice': 'zh_female_vv_uranus_bigtts',
'volcEncoding': encoding,
'ttsSpeed': 1.0,
},
}
t0 = time.time()
chunks = 0
total = 0
first_at = None
mime = ''
try:
for mime, chunk in speech.synthesize_stream(TEXT, settings):
chunks += 1
total += len(chunk)
if first_at is None:
first_at = time.time() - t0
except speech.SpeechError as exc:
print(f' [{encoding}] 失败: {exc}')
failed += 1
continue
last_at = time.time() - t0
# 首块明显早于末块 = 边生成边下发。用 0.6 当阈值:
# 真流式下首块通常只占总时长的两成左右,攒完再发的话两者几乎相等。
streamed = first_at is not None and first_at < last_at * 0.6
if not streamed:
failed += 1
print(f' [{encoding}] mime={mime} {chunks} 块 / {total} 字节')
print(f' 首块 {first_at * 1000:.0f}ms 末块 {last_at * 1000:.0f}ms '
f'{"[OK] 边生成边给" if streamed else "[FAIL] 疑似攒完才给"}')
print(f'\n {"全部通过" if failed == 0 else str(failed) + " 项失败"}')
sys.exit(1 if failed else 0)