Files
doubao-clone/scripts/verify-tts-stream.py
l a85a8858bf 边生成边读:实测 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 边收边播。
2026-10-09 17:44:35 +08:00

62 lines
2.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""实测 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)