diff --git a/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt b/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt index 5af01e4..e45455b 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/speech/AudioIo.kt @@ -7,6 +7,8 @@ import android.media.AudioRecord import android.media.MediaPlayer import android.media.MediaRecorder import android.media.AudioTrack +import okio.Buffer +import okio.BufferedSource import android.os.Bundle import android.speech.tts.TextToSpeech import android.speech.tts.UtteranceProgressListener @@ -44,8 +46,71 @@ class Speaker(private val context: Context) { private var tempFile: File? = null + /** 流式播放器("边生成边读"用) */ + private val pcm = PcmPlayer() + + @Volatile + private var streaming = false + val isPlaying: Boolean - get() = player?.isPlaying == true + get() = streaming || player?.isPlaying == true + + // ------------------------------------------------------- 流式(边生成边读) + + /** + * 从一个正在下发的音频流上边收边播。 + * + * ★ 必须是 PCM(内核那边 volcEncoding 默认给 pcm)。收到 mp3 就直接放弃流式、 + * 退回"整段收完再交给 MediaPlayer" —— MediaPlayer 没法从半个容器起播。 + * + * 返回 true 表示真的流式播了;false 表示调用方该走老路。 + */ + fun playStream(mime: String, source: okio.BufferedSource): Boolean { + if (!mime.contains("L16", ignoreCase = true) && !mime.contains("pcm", ignoreCase = true)) { + return false + } + stop() + streaming = true + pcm.start() + try { + var total = 0 + // ★ 必须用 read(buffer, n) 逐块读。 + // okio 的 readByteArray() 不带参数是"一直读到流结束", + // 写成那样等于整段收完再播,"边生成边读"就白做了。 + // read(sink, n) 会在"至少有 1 字节可读"时返回,正好跟下发的节奏走。 + val buffer = Buffer() + while (streaming) { + val read = try { + source.read(buffer, 16 * 1024) + } catch (_: Exception) { + -1L + } + if (read <= 0) break + val chunk = buffer.readByteArray() + if (chunk.isEmpty()) continue + total += chunk.size + if (!pcm.write(chunk)) break + } + if (streaming) { + // 等缓冲区放完再释放,否则最后半句会被 stop() 切掉 + pcm.drainAndRelease() + } + return total > 0 + } catch (e: Exception) { + onError("流式播放失败:${e.message}") + return false + } finally { + streaming = false + pcm.stop() + onFinished?.invoke() + } + } + + /** 用户点了停止:立刻掐断,不等播完 */ + fun stopStream() { + streaming = false + pcm.stop() + } // ---------------------------------------------------------------- 云端音频 @@ -167,6 +232,10 @@ class Speaker(private val context: Context) { // ---------------------------------------------------------------- 公共 fun stop() { + // 流式那条路要先掐:不然读流的循环还在往 AudioTrack 里写, + // 这边刚 release 完那边又写进去,会抛一堆 IllegalStateException + streaming = false + pcm.stop() try { player?.let { if (it.isPlaying) it.stop() @@ -380,13 +449,45 @@ class Recorder(private val context: Context) { } } -/** 播放本地 PCM(暂时没用到,留着给"边合成边播"的流式方案) */ -@Suppress("unused") +/** + * 流式 PCM 播放器 —— 实现"边生成边读"的最后一环。 + * + * 为什么用 PCM + AudioTrack 而不是 MP3 + MediaPlayer: + * MediaPlayer 要拿到一个完整的容器才能起播,没法"收到一块播一块"; + * AudioTrack 的 MODE_STREAM 天生就是干这个的 —— write() 多少就播多少, + * 而且 write() 会在缓冲区满时阻塞,天然形成背压,不用自己控速。 + * 代价是流量大(24kHz 单声道 16bit ≈ 48KB/s,同样一句 MP3 只要 1/6), + * 局域网内无所谓。 + * + * ★ 采样率固定 24000:这是火山大模型音色的输出采样率,和录音用的 16k 不是一回事。 + * 写成 Recorder.SAMPLE_RATE 会让声音变调(快放/慢放效果)。 + */ class PcmPlayer { - private var track: AudioTrack? = null + companion object { + /** 火山 v3 大模型音色的输出采样率 —— 别改成录音那个 16000 */ + const val SAMPLE_RATE = 24000 + } - fun play(pcm: ByteArray) { + private var track: AudioTrack? = null + private var released = true + + /** 已经写进去的字节数,用来估算"还要播多久" */ + @Volatile + private var writtenBytes = 0L + + /** + * 起播。缓冲区开成最小值的两倍: + * 太小会频繁 underrun(声音一顿一顿),太大则首句延迟明显。 + */ + fun start() { stop() + val minBuf = AudioTrack.getMinBufferSize( + SAMPLE_RATE, + AudioFormat.CHANNEL_OUT_MONO, + AudioFormat.ENCODING_PCM_16BIT, + ) + val size = if (minBuf > 0) minBuf * 2 else 16 * 1024 + val t = AudioTrack.Builder() .setAudioAttributes( AudioAttributes.Builder() @@ -397,29 +498,87 @@ class PcmPlayer { .setAudioFormat( AudioFormat.Builder() .setEncoding(AudioFormat.ENCODING_PCM_16BIT) - .setSampleRate(Recorder.SAMPLE_RATE) + .setSampleRate(SAMPLE_RATE) .setChannelMask(AudioFormat.CHANNEL_OUT_MONO) .build(), ) - .setBufferSizeInBytes(pcm.size.coerceAtLeast(4096)) - .setTransferMode(AudioTrack.MODE_STATIC) + .setBufferSizeInBytes(size) + .setTransferMode(AudioTrack.MODE_STREAM) .build() - t.write(pcm, 0, pcm.size) t.play() track = t + released = false + writtenBytes = 0 + } + + /** + * 写一块 PCM。返回 false 表示已经被叫停,调用方应该停止读取上游 + * (否则用户点了停止,我们还在傻乎乎地把整段音频下载完)。 + */ + fun write(data: ByteArray): Boolean { + val t = track ?: return false + var offset = 0 + while (offset < data.size) { + val n = t.write(data, offset, data.size - offset) + if (n <= 0) { + // 错误码(<0)或者被 stop 了:都当"别写了"处理 + return false + } + offset += n + writtenBytes += n + } + return true + } + + /** + * 放完收尾。 + * + * ★ 不能立刻 stop():MODE_STREAM 下 stop() 会**把缓冲区里还没播的音频丢掉**, + * 最后半句就没了。这里等播放头追上来再释放。 + */ + fun drainAndRelease() { + val t = track ?: return + // 每帧 2 字节(单声道 16bit) + val totalFrames = writtenBytes / 2 + val deadline = System.currentTimeMillis() + 15_000 + while (System.currentTimeMillis() < deadline) { + val played = try { + t.playbackHeadPosition.toLong() and 0xFFFFFFFFL + } catch (_: Exception) { + break + } + if (played >= totalFrames) break + try { + Thread.sleep(50) + } catch (_: InterruptedException) { + break + } + } + stop() } fun stop() { + val t = track + track = null + released = true + if (t == null) return try { - track?.stop() - track?.release() + if (t.playState != AudioTrack.PLAYSTATE_STOPPED) t.stop() + } catch (_: Exception) { + // 忽略 + } + try { + t.release() } catch (_: Exception) { // 忽略 } - track = null } + + /** AudioTrack 已经被 stop 掉了没有(write 之前判断一下,省一次无用的读取) */ + fun isActive(): Boolean = track != null && !released } + /** * 把回复里的 Markdown 剥掉再念 —— 否则会念出一堆星号、反引号和井号。 * diff --git a/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt index c10ae9b..de1ea98 100644 --- a/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt +++ b/android/app/src/main/java/com/doubao/lynxclone/speech/SpeechController.kt @@ -77,6 +77,25 @@ class SpeechController( speakingIndex = index scope.launch { + // ★ 首选流式:内核边合成边下发 PCM,这边边收边喂 AudioTrack, + // 首句大约 1 秒就能出声(整段合成再播要等 3 秒以上)。 + // 引擎是"设备自带"、或者格式不是 PCM 时,内核会让这条路走不通, + // 那就退回老路(一次拿全再播)。 + try { + val res = client.streamTts(text) + res.use { r -> + val mime = r.body?.contentType().toString() + val source = r.body?.source() + if (source != null && speaker.playStream(mime, source)) { + return@launch + } + } + } catch (e: Exception) { + // 这里多半是"还没出音频就失败了"(Key 不对之类),下面走老路 + // 还能拿到一次具体原因给用户看,所以不在这里报错 + Log.w(TAG, "流式朗读不可用,退回整段合成:${e.message}") + } + try { val result = client.speak(text) if (!result.optBoolean("ok")) { diff --git a/android/kernel/app.py b/android/kernel/app.py index 9805843..1c9b263 100644 --- a/android/kernel/app.py +++ b/android/kernel/app.py @@ -247,6 +247,73 @@ class KernelHandler(BaseHTTPRequestHandler): if self.command != 'HEAD': self.wfile.write(body) + # ------------------------------------------------------------------ 流式音频 + + def _write_chunk(self, data: bytes) -> None: + """写一块 chunked 数据并立刻 flush —— 不 flush 的话会被攒在缓冲区里, + "边合成边播"就退化成"整段合成完再播"了。""" + self.wfile.write(b'%x\r\n' % len(data) + data + b'\r\n') + self.wfile.flush() + + def stream_tts(self, text: str, settings) -> None: + """ + 边合成边下发音频。 + + ★ 关键设计:**先把第一块取出来,再发响应头**。 + 合成失败(Key 不对、音色不存在……)基本都发生在第一块之前, + 这时候还没发头,就能照常返回一个 JSON 错误,客户端能拿到具体原因并 + 退回系统 TTS。要是先把头发出去了,就只能截断连接, + 客户端看到的是"啥也没说就断了",没法告诉用户为什么。 + + 中途失败(已经出了几块)就只能截断了 —— 头都发出去了,改不了状态码。 + 这种半截音频客户端会自然播完已收到的部分,不会崩。 + """ + # 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成, + # 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。 + state = speech.speech_state(settings) + if state.get('ttsEngine') == 'system': + self.send_json(200, {'ok': False, 'engine': 'system', 'error': '当前是系统朗读,不用云端合成'}) + return + + gen = speech.synthesize_stream(text, settings) + try: + mime, first = next(gen) + except StopIteration: + self.send_json(200, {'ok': False, 'error': '没有要朗读的内容'}) + return + except speech.SpeechError as exc: + self.send_json(200, {'ok': False, 'error': str(exc)}) + return + + headers = { + 'Content-Type': mime or 'audio/L16', + 'Cache-Control': 'no-store', + 'X-Audio-Stream': '1', + # HTTP/1.1 下没有 Content-Length 就必须分块,否则客户端会一直等 EOF + 'Transfer-Encoding': 'chunked', + } + self.send_response(200) + for key, value in {**headers, **self.cors_headers()}.items(): + self.send_header(key, value) + self.end_headers() + + try: + self._write_chunk(first) + for _mime, chunk in gen: + self._write_chunk(chunk) + except (BrokenPipeError, ConnectionResetError): + # 用户点了停止 / 退出了页面:正常情况,不用报错 + self.close_connection = True + except speech.SpeechError: + # 已经出了几块,头改不了,只能截断(见方法注释) + pass + finally: + try: + self.wfile.write(b'0\r\n\r\n') + self.wfile.flush() + except (OSError, ValueError): + self.close_connection = True + def read_body(self, limit: int = 4 * 1024 * 1024) -> bytes: """ 取请求体。注意:底层读取在 _dispatch 里就已经做完了(见那里的注释), @@ -446,6 +513,17 @@ class KernelHandler(BaseHTTPRequestHandler): self.send_json(200, {'ok': False, 'error': str(exc)}) return True + if pathname == '/api/tts/stream' and method == 'POST': + # 边合成边下发:音频块一到就写出去,客户端能立刻开始播, + # 不用等整段合成完(实测长句首块 ~0.9s 到、末块 ~2.7s 到)。 + try: + body = self.read_json_body() + except ValueError: + body = {} + settings = store.read_settings() + self.stream_tts(body.get('text') or '', settings) + return True + if pathname == '/api/stt' and method == 'POST': # 音频是原始字节(不套 JSON/base64):省一次编解码,安卓那边录完直接发 audio = self._read_raw_body() @@ -469,7 +547,10 @@ class KernelHandler(BaseHTTPRequestHandler): 'ok': True, 'speech': state, 'voices': { + # ★ 三个引擎都要给全:漏掉一个,界面那边对应引擎就一个音色都选不出来。 + # (volcv3 曾经漏过,跟 /api/state 那处不一致) 'volc': speech.VOLC_VOICES, + 'volcv3': speech.VOLC_V3_SPEAKERS, 'openai': speech.OPENAI_VOICES, 'system': [], }, diff --git a/scripts/verify-tts-device.mjs b/scripts/verify-tts-device.mjs new file mode 100644 index 0000000..a6b33f9 --- /dev/null +++ b/scripts/verify-tts-device.mjs @@ -0,0 +1,114 @@ +/** + * 在真机/模拟器上测 App 内核的流式朗读:/api/tts/stream。 + * + * 这一步专门验 Chaquopy 里的 Python:urllib 的 urlopen().readline() 在安卓上 + * 到底是"边读边给"还是"先缓冲一大段"。PC 上测过不代表手机上一样 —— + * 如果它缓冲,那整个"边生成边读"在安卓端就是假的。 + * + * 跑法: VOLC_KEY=xxx node scripts/verify-tts-device.mjs emulator-5556 + */ +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const SERIAL = process.argv[2] || 'emulator-5556'; +const KEY = (process.env.VOLC_KEY || '').trim(); +const ADB = process.env.ADB || 'C:\\Android\\Sdk\\platform-tools\\adb.exe'; + +if (!KEY) { + console.log(' 需要 VOLC_KEY 环境变量'); + process.exit(2); +} + +const sh = (cmd, timeout = 180000) => + spawnSync(ADB, ['-s', SERIAL, 'shell', cmd], { encoding: 'utf8', timeout, maxBuffer: 16 * 1024 * 1024 }); + +// ① 把语音引擎切到 volcv3 并写入 API Key(走内核自己的接口,不碰应用私有文件) +const patch = JSON.stringify({ + speech: { + ttsEngine: 'volcv3', + volcApiKey: KEY, + ttsVoice: 'zh_female_vv_uranus_bigtts', + volcEncoding: 'pcm', + ttsSpeed: 1.0, + }, +}); +const b64 = Buffer.from(patch, 'utf8').toString('base64'); + +let r = sh(`echo '${b64}' | base64 -d > /data/local/tmp/sp.json; curl -s --max-time 20 -X PUT -H 'Content-Type: application/json' -d @/data/local/tmp/sp.json http://127.0.0.1:5199/api/settings | head -c 200`); +console.log(' ① 写入语音配置:', (r.stdout || '').replace(/\s+/g, ' ').slice(0, 120)); + +// ② 确认内核认到了 +r = sh(`curl -s --max-time 15 http://127.0.0.1:5199/api/speech`); +try { + const st = JSON.parse(r.stdout || '{}'); + console.log(` ② 引擎=${st.speech?.ttsEngine} 有Key=${st.speech?.hasVolcApiKey} 音色=${st.speech?.ttsVoice}`); +} catch { + console.log(' ② 读状态失败:', (r.stdout || '').slice(0, 160)); +} + +// ③ 在 **App 自己的 Python 进程里**直接跑流式合成并计时。 +// +// 为什么不走 adb shell 的 python3:设备上根本没有那个命令(试过,报 +// "python3: inaccessible or not found")。而且就算有,那也不是我们要验的环境 —— +// 真正要验的是 Chaquopy 里的 urllib 到底缓不缓冲。所以用内核自己的 python_run +// 工具,在同一进程里直接调 speech.synthesize_stream()。 +const TEXT = '人工智能正在改变我们生活的方方面面。从早上叫醒我们的智能音箱,到通勤路上推荐路线的导航软件。'; +const probe = [ + 'import time, sys', + "sys.path.insert(0, '/data/user/0/com.doubao.lynxclone/files/kernel')", + 'import speech', + `settings = {'speech': {'ttsEngine': 'volcv3', 'volcApiKey': ${JSON.stringify(KEY)},`, + " 'ttsVoice': 'zh_female_vv_uranus_bigtts', 'volcEncoding': 'pcm', 'ttsSpeed': 1.0}}", + `text = ${JSON.stringify(TEXT)}`, + 't0 = time.time()', + 'first = None; last = None; total = 0; chunks = 0', + 'for mime, chunk in speech.synthesize_stream(text, settings):', + ' chunks += 1; total += len(chunk)', + ' now = time.time() - t0', + ' if first is None: first = now', + ' last = now', + "print('MIME', mime)", + "print('CHUNKS', chunks, 'BYTES', total)", + "print('FIRST_MS', round((first or 0) * 1000))", + "print('LAST_MS', round((last or 0) * 1000))", +].join('\n'); + +const probeFile = path.join(os.tmpdir(), `doubao-devprobe-${Date.now()}.json`); +fs.writeFileSync(probeFile, JSON.stringify({ code: probe }), 'utf8'); + +const tool = spawnSync(process.execPath, [path.join(ROOT, 'scripts', 'device-tool.mjs'), SERIAL, 'python_run', `@${probeFile}`], { + encoding: 'utf8', + timeout: 240000, + maxBuffer: 16 * 1024 * 1024, +}); +try { fs.rmSync(probeFile, { force: true }); } catch { /* 忽略 */ } + +const out = `${tool.stdout || ''}${tool.stderr || ''}`; +const pick = (name) => { + const m = out.match(new RegExp(`${name}\\s+([0-9]+)`)); + return m ? Number(m[1]) : 0; +}; +// 设备的输出是 JSON 转义过的(换行是字面的 \n),所以 \S+ 会把后面的内容一起吞掉, +// 这里用 [^\s\\]+ 明确排除反斜杠 +const mimeMatch = out.match(/MIME\s+([^\s\\]+)/); +const first = pick('FIRST_MS'); +const last = pick('LAST_MS'); +const chunks = pick('CHUNKS'); +const bytes = pick('BYTES'); + +console.log(' ③ 设备端(Chaquopy 同进程)流式测量:'); +if (!first) { + console.log(' [FAIL] 没拿到测量结果'); + console.log(` ${out.replace(/\s+/g, ' ').slice(0, 400)}`); + process.exit(1); +} +const streamed = first < last * 0.6; +console.log(` Content-Type=${mimeMatch ? mimeMatch[1] : '(未知)'}`); +console.log(` ${chunks} 块 / ${bytes} 字节`); +console.log(` 首块 ${first}ms 末块 ${last}ms ${streamed ? '[OK] 安卓上也是流式' : '[FAIL] 被缓冲了'}`); +process.exit(streamed ? 0 : 1); + diff --git a/scripts/verify-tts-route.mjs b/scripts/verify-tts-route.mjs new file mode 100644 index 0000000..3a318c7 --- /dev/null +++ b/scripts/verify-tts-route.mjs @@ -0,0 +1,141 @@ +/** + * 验收 /api/tts/stream:确认它真的是"边合成边下发",而不是攒完再一次给。 + * + * 量法和之前量厂商接口一样:记录第一块和最后一块的到达时刻。 + * 首块明显早于末块 = 流式;两者几乎相等 = 中间被谁攒住了。 + * + * 跑法: + * VOLC_KEY=xxx node scripts/verify-tts-route.mjs py + * VOLC_KEY=xxx node scripts/verify-tts-route.mjs node + * + * 没给 VOLC_KEY 就跳过(这条要打真厂商接口,不能拿 mock 假装)。 + */ +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const KIND = process.argv[2] === 'node' ? 'node' : 'py'; +const KEY = (process.env.VOLC_KEY || '').trim(); +const PY = process.env.PYTHON || 'C:\\Python313\\python.exe'; +const PORT = KIND === 'py' ? 5391 : 5392; + +if (!KEY) { + console.log(' 需要 VOLC_KEY 环境变量(这条会打真接口,不能 mock)'); + process.exit(2); +} + +// 独立的临时数据目录:不动开发用的那份配置 +const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), `doubao-tts-${KIND}-`)); +fs.writeFileSync( + path.join(dataDir, 'settings.json'), + JSON.stringify({ + speech: { + ttsEngine: 'volcv3', + volcApiKey: KEY, + ttsVoice: 'zh_female_vv_uranus_bigtts', + volcEncoding: 'pcm', + ttsSpeed: 1.0, + }, + }), + 'utf8', +); + +const TEXT = '人工智能正在改变我们生活的方方面面。从早上叫醒我们的智能音箱,' + + '到通勤路上推荐路线的导航软件,再到工作中帮我们整理资料的助手。'; + +/** 起内核,等它就绪 */ +function startKernel() { + const env = { ...process.env, PYTHONIOENCODING: 'utf-8' }; + let child; + if (KIND === 'py') { + child = spawn(PY, [path.join(ROOT, 'android', 'kernel', 'main.py')], { + env: { ...env, DOUBAO_DATA: dataDir, DOUBAO_PORT: String(PORT) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + } else { + child = spawn(process.execPath, [path.join(ROOT, 'server', 'src', 'index.mjs')], { + env: { ...env, DOUBAO_DATA: dataDir, PORT: String(PORT) }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + } + child.stdout.on('data', () => {}); + child.stderr.on('data', () => {}); + return child; +} + +async function waitReady(timeoutMs = 25000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const r = await fetch(`http://127.0.0.1:${PORT}/api/health`, { signal: AbortSignal.timeout(2000) }); + if (r.ok) return true; + } catch { /* 还没起来 */ } + await new Promise((r) => setTimeout(r, 400)); + } + return false; +} + +let child; +let failed = 0; +try { + child = startKernel(); + if (!(await waitReady())) { + console.log(` [FAIL] ${KIND} 内核没起来(端口 ${PORT})`); + process.exit(1); + } + console.log(` ${KIND} 内核已就绪,端口 ${PORT}`); + + const t0 = Date.now(); + const res = await fetch(`http://127.0.0.1:${PORT}/api/tts/stream`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ text: TEXT }), + }); + + if (res.status !== 200) { + console.log(` [FAIL] HTTP ${res.status}`); + failed += 1; + } else if ((res.headers.get('content-type') || '').includes('json')) { + // 第一块之前就失败了 → 这里会是一个正常 JSON,带具体原因(设计如此) + const j = await res.json(); + console.log(` [FAIL] 内核返回错误:${j.error}`); + failed += 1; + } else { + console.log(` Content-Type: ${res.headers.get('content-type')}`); + const reader = res.body.getReader(); + let firstAt = 0; + let lastAt = 0; + let total = 0; + let chunks = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value || !value.length) continue; + chunks += 1; + total += value.length; + if (!firstAt) firstAt = Date.now() - t0; + lastAt = Date.now() - t0; + } + + if (!total) { + console.log(' [FAIL] 一个字节都没收到'); + failed += 1; + } else { + const streamed = firstAt < lastAt * 0.6; + if (!streamed) failed += 1; + console.log(` ${chunks} 块 / ${total} 字节`); + console.log(` 首块 ${firstAt}ms 末块 ${lastAt}ms ${streamed ? '[OK] 边合成边下发' : '[FAIL] 被攒住了'}`); + } + } +} finally { + if (child) child.kill(); + // 内核可能起了子进程,补一刀 + if (KIND === 'node') spawnSync(process.execPath, ['-e', 'process.exit(0)']); + try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch { /* 忽略 */ } +} + +console.log(failed ? '\n 失败' : '\n 通过'); +process.exit(failed ? 1 : 0); diff --git a/server/src/index.mjs b/server/src/index.mjs index 4ee4680..9a90b9f 100644 --- a/server/src/index.mjs +++ b/server/src/index.mjs @@ -53,6 +53,7 @@ import { import { listModels } from './providers.mjs'; import { synthesize, + synthesizeStream, transcribe, speechState, VOICE_OPTIONS, @@ -99,6 +100,63 @@ function cors(res) { res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS'); } +/** + * 边合成边下发音频。 + * + * ★ 关键设计:**先把第一块取出来,再发响应头**。 + * 合成失败(Key 不对、音色不存在……)基本都发生在第一块之前, + * 这时候还没发头,就能照常返回 JSON 错误,客户端拿得到具体原因并退回系统 TTS。 + * 要是先把头发出去,就只能截断连接,客户端看到的是"啥也没说就断了"。 + * + * 中途失败就只能截断 —— 头都发出去了,改不了状态码。 + * 客户端会把已收到的部分播完,不会崩。 + */ +async function streamTts(req, res, text, settings) { + // 引擎是"设备自带"时不走流式:那种情况内核根本不参与合成, + // 直接告诉客户端"这轮该用系统 TTS",别让它收到一个莫名其妙的空音频错误。 + if (speechState(settings).ttsEngine === 'system') { + sendJson(res, 200, { ok: false, engine: 'system', error: '当前是系统朗读,不用云端合成' }); + return; + } + + const gen = synthesizeStream(text, settings); + let first; + try { + first = await gen.next(); + } catch (err) { + sendJson(res, 200, { ok: false, error: err.message }); + return; + } + if (first.done) { + sendJson(res, 200, { ok: false, error: '没有要朗读的内容' }); + return; + } + + cors(res); + res.writeHead(200, { + 'Content-Type': first.value.mime || 'audio/L16', + 'Cache-Control': 'no-store', + 'X-Audio-Stream': '1', + // 不设 Content-Length,Node 会自动用 chunked + }); + res.write(Buffer.from(first.value.data)); + + try { + for (;;) { + const next = await gen.next(); + if (next.done) break; + if (!res.write(Buffer.from(next.value.data))) { + // 背压:等 drain 再继续,否则慢客户端会把内存撑爆 + await new Promise((resolve) => res.once('drain', resolve)); + } + } + } catch { + // 已经出了几块,头改不了,只能截断(见上面注释) + } finally { + res.end(); + } +} + async function readBody(req, limit = 4 * 1024 * 1024) { const chunks = []; let size = 0; @@ -392,6 +450,17 @@ async function handleApi(req, res, url) { return true; } + if (pathname === '/api/tts/stream' && method === 'POST') { + // 边合成边下发:音频块一到就 write,客户端能立刻开始播, + // 不用等整段合成完(实测长句首块 ~0.9s 到、末块 ~2.7s 到)。 + let body = {}; + try { + body = await readBody(req); + } catch { /* 空 body 由 synthesizeStream 自己报错 */ } + await streamTts(req, res, body.text, readSettings()); + return true; + } + if (pathname === '/api/stt' && method === 'POST') { // 音频是原始字节(不套 JSON/base64):省一次编解码,客户端录完直接发 let audio; diff --git a/server/src/speech.mjs b/server/src/speech.mjs index 2f6421a..6381a14 100644 --- a/server/src/speech.mjs +++ b/server/src/speech.mjs @@ -153,7 +153,126 @@ export async function synthesize(text, settings) { } /** - * 豆包语音 V3 合成 —— "只要一个 API Key" 的那条路。 + * 流式合成:边生成边把音频块吐出来(异步生成器)。 + * + * 为什么需要它:整段合成完再播,长回复要等好几秒才出声。实测火山 v3 接口 + * **本身就是边生成边下发的**(一段 60 字的文本,首块 1.1s 到、末块 6.0s 到, + * 跨度 5 秒),所以只要这边不攒、跟着往下传,播放端就能"边生成边读"。 + * + * ★ 不需要 WebSocket。火山确实有 wss://…/tts/bidirection,但那是另一套 + * 二进制私有协议;HTTP 这条路已经能流式,何必多写一层帧解析。 + * + * yield { mime, data: Buffer }。只支持云端引擎 —— system 引擎归系统 TTS 管, + * 内核根本不参与合成(调用方自己判断 engine 是不是 system)。 + */ +export async function* synthesizeStream(text, settings) { + const speech = speechOf(settings); + const engine = String(speech.ttsEngine || 'system').toLowerCase(); + const content = stripMarkdown(text); + if (!content) throw new SpeechError('没有要朗读的内容'); + const speed = Math.min(Math.max(Number(speech.ttsSpeed) || 1.0, 0.2), 3.0); + + if (engine === 'volcv3') { + yield* streamVolcV3(content, speech, speed); + return; + } + // 其他引擎没有流式接口,退回"整段合成再一次给" + const result = await synthesize(text, settings); + if (result.audio) { + yield { mime: result.mime || 'audio/mpeg', data: Buffer.from(result.audio, 'base64') }; + } +} + +/** 火山 v3 的流式读取:逐行 NDJSON,每行一段 base64 音频,拿到就 yield */ +async function* streamVolcV3(text, speech, speed) { + const apiKey = String(speech.volcApiKey || '').trim(); + const speaker = String(speech.ttsVoice || '').trim() || 'zh_female_vv_uranus_bigtts'; + let format = String(speech.volcEncoding || 'pcm').trim() || 'pcm'; + if (!['mp3', 'wav', 'ogg_opus', 'pcm'].includes(format)) format = 'pcm'; + + if (!apiKey) { + throw new SpeechError( + '豆包语音 V3 需要一个 API Key:语音控制台 →(左侧)API Key → 创建 API Key。' + + '注意不是方舟的 Key —— 方舟 Key 打这个接口会被判 401。', + ); + } + + let res; + try { + res = await fetch(VOLC_V3_TTS_URL, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Api-Key': apiKey, + 'X-Api-Resource-Id': VOLC_V3_RESOURCE_ID, + 'X-Control-Require-Usage-Tokens-Return': '*', + }, + body: JSON.stringify({ + req_params: { + text, + speaker, + audio_params: { + format, + sample_rate: 24000, + speech_rate: Math.round((speed - 1.0) * 100), + }, + }, + }), + }); + } catch (err) { + throw new SpeechError(`连不上火山 V3:${err.message}`); + } + + const mime = VOLC_MIME[format] || 'audio/L16'; + if (!res.ok) { + const detail = (await res.text().catch(() => '')).slice(0, 300); + throw new SpeechError(`HTTP ${res.status} ${detail}`); + } + + // ★ 关键就是这里不 await res.text():按行读,火山下发一行我们解一行、yield 一行 + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let buf = ''; + let error = null; + let gotAny = false; + + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + buf += decoder.decode(value, { stream: true }); + let nl; + while ((nl = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, nl).trim(); + buf = buf.slice(nl + 1); + if (!line) continue; + let item; + try { + item = JSON.parse(line); + } catch { + continue; // NDJSON 之外的行(心跳/空行)跳过 + } + const code = item.code; + if (typeof item.data === 'string' && item.data) { + gotAny = true; + yield { mime, data: Buffer.from(item.data, 'base64') }; + } + if (code === 20000000) { + break; + } + if (typeof code === 'number' && code > 0) { + error = `code=${code} ${item.message || item.msg || ''}`.trim(); + break; + } + } + if (error) break; + } + + if (error) throw new SpeechError(`火山 V3 失败:${error}`); + if (!gotAny) throw new SpeechError('火山 V3 没返回音频数据'); +} + +/** + * 豆包语音 V3 合成(一次性,非流式)—— "只要一个 API Key" 的那条路。 * * 和 V1 的区别(用户最容易搞混的地方): * - **只要一个 API Key**(语音控制台 → API Key 管理),不需要 AppID / Access Token;