语音加 V3(只要一个 API Key)+ 各控制台快捷入口 + 对话支持 Markdown

【语音 V3:用户要的"一个 Key 搞定"那条路】
之前我给的方案是 V1(AppID + Access Token),用户问"不是只要 api key 就行了吗"——
他是对的。查官方文档确认 V3 用 X-Api-Key,不用 appid:
  https://docs.volcengine.com/docs/DoubaoVoice/APIKeyUsage

实测踩到两个坑,都已写进注释:
  1. 路径不能带 plan。/api/v3/plan/tts/unidirectional 是方舟 Agent Plan 专用,
     语音控制台的 Key 打过去 401;/api/v3/tts/unidirectional 才通(返回真 MP3)。
  2. 普通**方舟** Key 也不行,会回 `acquire failed err:call ark 401` ——
     必须是语音控制台「API Key 管理」里建的那个。
三个 Key 逐个测过,结论写进了错误提示里,用户一看就知道该去哪儿拿。

V3 音色是另一套命名(zh_female_vv_uranus_bigtts),和 V1 的 BVxxx 完全不通用。
8 个音色实测都能合成,名字照官方音色列表核对。

【各控制台快捷入口】
设置页每个提供商下面多一行「去 XX 申请 API Key ↗」,语音卡片同理。
地址放在内核的一张表里(PROVIDER_CONSOLE_URLS / SPEECH_CONSOLE_URLS)而不是
写死在界面:实测 Kimi 已经从 platform.moonshot.cn 迁到 platform.kimi.com,
集中一处以后好改。每个地址都访问核实过可达。

【对话 Markdown】
自写了个轻量渲染(零依赖是这个项目的既定约束):
块级支持代码块 / 标题 / 列表 / 引用 / 分隔线,行内支持粗体斜体行内码链接删除线。
只对助手回复渲染 —— 用户输入里的 `2 * 3 * 4` 会被当成斜体,显示得和打的不一样。

【验收】
verify-speech.mjs 扩到 36 项,含 V3 音色表、命名不混用、控制台链接下发。
Node 与 Python 两份内核对拍全过 —— 这轮就是靠它抓到 Node 侧漏了 VOLC_V3_SPEAKERS。

【豆包搜索:已调通接口,但需要先开通】
接口形状摸清了(POST /api/v3/responses + tools:[{"type":"web_search"}]),
用有效方舟 Key 实测返回 403 Access denied for web search,
需要在方舟控制台「应用组件库 > 豆包搜索」开通服务后才可用。开通后即可接入。
This commit is contained in:
l
2026-10-09 16:28:55 +08:00
parent b8c6bd6f59
commit e693b84e2e
10 changed files with 798 additions and 16 deletions

View File

@@ -34,6 +34,19 @@ DEFAULT_TIMEOUT_STT = 120
# (鉴权头那个分号、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',
@@ -99,11 +112,101 @@ def synthesize(text: str, settings: dict) -> dict:
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:
"""
火山语音合成。
@@ -302,12 +405,29 @@ def speech_state(settings: dict) -> dict:
'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',
}
# 默认值:Android 端 Kotlin 侧也用不到这个,但 Node/Python 必须一致
DEFAULT_SPEECH = {
'ttsEngine': 'system',
@@ -319,6 +439,7 @@ DEFAULT_SPEECH = {
'sttLanguage': '',
'volcAppId': '',
'volcToken': '',
'volcApiKey': '', # V3 用的那个(语音控制台 → API Key 管理)
'volcCluster': 'volcano_tts',
'volcEncoding': 'mp3',
'openaiApiKey': '',
@@ -357,10 +478,26 @@ OPENAI_VOICES = [
{'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 []