修:语音读一半就不读了、时长不定(自动朗读被反复重入掐断)
接上一条。上一条我改了收尾死线(15 秒写死 → 按音频长度算),但用户说
"还是断,时长不定"。**"时长不定"这个描述是关键** —— 如果是死线问题,
每次都会断在固定时长;不定就说明另有原因。
于是加了个决定性的观测:把每次流式朗读的结果写进
kernel-data/tts-trace.log(ROM 把 logcat 全吞了,只能写文件)。
一条记录就能回答"音频是我们没发完,还是客户端提前断开"。
拿到的新旧两轮数据:
修之前(同一段 179 字文本被请求 3 次):
client_aborted(BrokenPipeError) 28.3 秒音频
client_aborted(BrokenPipeError) 20.4 秒音频 ← 断点不一样
completed 37.1 秒音频
修之后(3 次):
completed / completed / completed ← 一次都没被提前断开
根因(两个叠在一起):
1. 自动朗读那个 LaunchedEffect 的 key 里带了 content.length。
流式增量、以及回复落地后 vm.refresh() 把消息换成本地存储版本,
都会让它重跑。
2. 而 speak() 对"同一条消息 + 正在播"的语义是**停止**(手动再点一次就是停,
这个语义对用户点击是对的)。自动朗读是**被动**触发的,重跑一次就掐一次。
3. 更要命的是竞态:speak() 里 speakingIndex 立刻赋值,但 speaker 真正开始播
要等一次网络往返(合成首块约 1 秒)——**那一秒里 isPlaying 还是 false**,
所以"正在播就别重入"这个守卫挡不住。
改法:
- effect 的 key 去掉 content.length,只留 size + pending
- maybeAutoRead 记住"这条消息已经自动念过了"(序号:文本长度),同一段不再重复触发
- 手动点朗读时清掉这个记录,保证用户主动点仍然正常(含再点一次停)
顺带把 stream_tts 的异常分支补全:以前只接 BrokenPipe/ConnectionReset 和
SpeechError,其它异常会让请求线程静默结束、追踪也记不上。
顺手加的观测能力(以后这类问题不用再猜):
- kernel-data/tts-trace.log:每次朗读一行,含 outcome / 字节数 / 音频秒数 / 耗时
- scripts/mock-llm.mjs 支持 MOCK_REPLY_CHARS(有一类 bug 只有长内容才暴露)
实测:修复后设备上连续 3 次自动朗读全部 completed,0 次中断。
测试期间临时开过 autoRead,跑完已恢复为 false。
This commit is contained in:
@@ -143,13 +143,39 @@ class SpeechController(
|
|||||||
speakingIndex = -1
|
speakingIndex = -1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 已经自动念过的消息("序号:文本长度")。
|
||||||
|
*
|
||||||
|
* 光靠"正在播就别重入"挡不住竞态:speak() 里 speakingIndex 是立刻赋值的,
|
||||||
|
* 但 speaker 真正开始播要等一次网络往返(合成首块,约 1 秒)——
|
||||||
|
* **那一秒里 isPlaying 还是 false**,此时重入就会走 speak() 的
|
||||||
|
* "同一条 + 没在播 = 重新开始"分支,把刚发起的朗读掐掉重来。
|
||||||
|
* 内核实测到同一条消息被请求三次、前两次都被客户端提前断开(断点还不一样,
|
||||||
|
* 用户感知就是"读一半就不读了,时长不定")。
|
||||||
|
*
|
||||||
|
* 所以记下"这条已经念过了",同一段文本不再自动重复触发。
|
||||||
|
*/
|
||||||
|
private var lastAutoReadKey: String? = null
|
||||||
|
|
||||||
/** 自动朗读:新回复刚落地时调它 */
|
/** 自动朗读:新回复刚落地时调它 */
|
||||||
fun maybeAutoRead(text: String, index: Int) {
|
fun maybeAutoRead(text: String, index: Int) {
|
||||||
if (!autoRead || text.isBlank()) return
|
if (!autoRead || text.isBlank()) return
|
||||||
if (recording) return
|
if (recording) return
|
||||||
|
|
||||||
|
val key = "$index:${text.length}"
|
||||||
|
if (key == lastAutoReadKey) return
|
||||||
|
// 正在念这一条也别重入 —— 绝不落到 speak() 那个"再点一次就是停"的分支
|
||||||
|
if (speakingIndex == index && speaker.isPlaying) return
|
||||||
|
|
||||||
|
lastAutoReadKey = key
|
||||||
speak(text, index)
|
speak(text, index)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 手动点朗读时清掉自动朗读的记录,免得"念过了就不再自动念"影响到后面 */
|
||||||
|
fun forgetAutoRead() {
|
||||||
|
lastAutoReadKey = null
|
||||||
|
}
|
||||||
|
|
||||||
/* ------------------------------ 录音 ------------------------------ */
|
/* ------------------------------ 录音 ------------------------------ */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -210,8 +210,14 @@ fun ChatScreen(vm: AppViewModel) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
|
// 自动朗读:最后一条回复从「进行中」变成「已落地」时念出来
|
||||||
|
//
|
||||||
|
// ★ key 里**不能带 content.length**。带上它的话,流式过程中的每一次增量、
|
||||||
|
// 以及回复落地后 vm.refresh() 把消息换成本地存储版本,都会让这个 effect 重跑;
|
||||||
|
// 而 speak() 对"同一条 + 正在播"的语义是**停止**(手动再点一次就是停),
|
||||||
|
// 于是每重跑一次就把朗读掐掉一次 —— 表现就是"读一半就不读了、时长不定"。
|
||||||
|
// 这里只留 size + pending:只在"多了一条消息 / 它从进行中变成完成"时重跑。
|
||||||
val lastMsg = vm.messages.lastOrNull()
|
val lastMsg = vm.messages.lastOrNull()
|
||||||
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}:${it.content.length}" }
|
val lastDoneKey = lastMsg?.let { "${vm.messages.size}:${it.pending}" }
|
||||||
LaunchedEffect(lastDoneKey) {
|
LaunchedEffect(lastDoneKey) {
|
||||||
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
|
val msg = vm.messages.lastOrNull() ?: return@LaunchedEffect
|
||||||
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
|
if (msg.role == "assistant" && !msg.pending && !msg.error && msg.content.isNotBlank()) {
|
||||||
@@ -595,7 +601,12 @@ private fun MessageItem(vm: AppViewModel, index: Int, msg: ChatMessage, speech:
|
|||||||
bg = doubaoHeroRing(),
|
bg = doubaoHeroRing(),
|
||||||
) { speech.stopSpeaking() }
|
) { speech.stopSpeaking() }
|
||||||
} else {
|
} else {
|
||||||
RoundIconButton(Icons.Filled.VolumeUp, "朗读") { speech.speak(msg.content, index) }
|
RoundIconButton(Icons.Filled.VolumeUp, "朗读") {
|
||||||
|
// 手动点朗读时清掉"自动朗读念过了"的记录:
|
||||||
|
// 用户主动点,就该正常播(或再点一次停),不受自动朗读的去重影响
|
||||||
|
speech.forgetAutoRead()
|
||||||
|
speech.speak(msg.content, index)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Spacer(Modifier.width(10.dp))
|
Spacer(Modifier.width(10.dp))
|
||||||
RoundIconButton(
|
RoundIconButton(
|
||||||
|
|||||||
@@ -125,6 +125,45 @@ def safe_join(root: str, url_path: str):
|
|||||||
return target
|
return target
|
||||||
|
|
||||||
|
|
||||||
|
def _trace_tts(text: str, outcome: str, total_bytes: int, chunks: int, seconds: float) -> None:
|
||||||
|
"""
|
||||||
|
把每次流式朗读的结果写一行到 kernel-data/tts-trace.log。
|
||||||
|
|
||||||
|
为什么不用 print/log:这台 ROM 把应用日志全吞了(logcat 里一条 app 记录都没有),
|
||||||
|
排查"读一半就不读了"时最要紧的问题是**音频是我们没发完,还是客户端提前断开**,
|
||||||
|
没有这个就只能在两边瞎猜。
|
||||||
|
|
||||||
|
outcome 的取值:
|
||||||
|
completed 正常发完
|
||||||
|
client_aborted(...) 客户端提前断开 —— 音频是它不要了
|
||||||
|
upstream_error(...) 厂商那边断了
|
||||||
|
kernel_error(...) 内核自己出错
|
||||||
|
按 48000 字节/秒能算出这段音频本该有多长,和实际耗时一比就知道断在哪。
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
path = os.path.join(paths.get().data_dir, 'tts-trace.log')
|
||||||
|
line = json.dumps({
|
||||||
|
'at': time.strftime('%m-%d %H:%M:%S'),
|
||||||
|
'textChars': len(text),
|
||||||
|
'outcome': outcome,
|
||||||
|
'bytes': total_bytes,
|
||||||
|
'audioSec': round(total_bytes / 48000.0, 1), # PCM 24k 单声道 16bit
|
||||||
|
'chunks': chunks,
|
||||||
|
'elapsedSec': round(seconds, 1),
|
||||||
|
}, ensure_ascii=False)
|
||||||
|
with open(path, 'a', encoding='utf-8') as fh:
|
||||||
|
fh.write(line + '\n')
|
||||||
|
# 只留最后 200 行,别让它无限长
|
||||||
|
with open(path, encoding='utf-8') as fh:
|
||||||
|
rows = fh.readlines()
|
||||||
|
if len(rows) > 200:
|
||||||
|
with open(path, 'w', encoding='utf-8') as fh:
|
||||||
|
fh.writelines(rows[-200:])
|
||||||
|
except Exception: # noqa: BLE001
|
||||||
|
# 追踪本身绝不能影响朗读
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
class SseChannel:
|
class SseChannel:
|
||||||
"""
|
"""
|
||||||
一条 SSE 连接。
|
一条 SSE 连接。
|
||||||
@@ -275,6 +314,11 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
self.send_json(200, {'ok': False, 'engine': 'system', 'error': '当前是系统朗读,不用云端合成'})
|
self.send_json(200, {'ok': False, 'engine': 'system', 'error': '当前是系统朗读,不用云端合成'})
|
||||||
return
|
return
|
||||||
|
|
||||||
|
# ★ 追踪写文件而不是打日志:这台 ROM 会把应用日志吞掉,排查时
|
||||||
|
# "到底是我们没发完还是客户端提前断开"根本无从判断。
|
||||||
|
total_bytes = 0
|
||||||
|
t0 = time.time()
|
||||||
|
|
||||||
gen = speech.synthesize_stream(text, settings)
|
gen = speech.synthesize_stream(text, settings)
|
||||||
try:
|
try:
|
||||||
mime, first = next(gen)
|
mime, first = next(gen)
|
||||||
@@ -299,20 +343,36 @@ class KernelHandler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
self._write_chunk(first)
|
self._write_chunk(first)
|
||||||
|
total_bytes += len(first)
|
||||||
|
chunks = 1
|
||||||
for _mime, chunk in gen:
|
for _mime, chunk in gen:
|
||||||
self._write_chunk(chunk)
|
self._write_chunk(chunk)
|
||||||
except (BrokenPipeError, ConnectionResetError):
|
total_bytes += len(chunk)
|
||||||
# 用户点了停止 / 退出了页面:正常情况,不用报错
|
chunks += 1
|
||||||
|
outcome = 'completed'
|
||||||
|
n_chunks = chunks
|
||||||
|
except (BrokenPipeError, ConnectionResetError) as exc:
|
||||||
|
# ★ 客户端提前断开 —— 这是判断"谁断的"的关键信号。
|
||||||
|
# 如果是这种,说明音频是客户端那边不要了(用户点了停止、或者播放端
|
||||||
|
# 自己退出了循环),不是我们没发完。
|
||||||
|
outcome = f'client_aborted({type(exc).__name__})'
|
||||||
|
n_chunks = 0
|
||||||
self.close_connection = True
|
self.close_connection = True
|
||||||
except speech.SpeechError:
|
except speech.SpeechError as exc:
|
||||||
# 已经出了几块,头改不了,只能截断(见方法注释)
|
# 已经出了几块,头改不了,只能截断(见方法注释)
|
||||||
pass
|
outcome = f'upstream_error({exc})'
|
||||||
|
n_chunks = 0
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
# 兜底:别让流式这条路的任何意外把请求线程带走
|
||||||
|
outcome = f'kernel_error({type(exc).__name__}: {exc})'
|
||||||
|
n_chunks = 0
|
||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
self.wfile.write(b'0\r\n\r\n')
|
self.wfile.write(b'0\r\n\r\n')
|
||||||
self.wfile.flush()
|
self.wfile.flush()
|
||||||
except (OSError, ValueError):
|
except (OSError, ValueError):
|
||||||
self.close_connection = True
|
self.close_connection = True
|
||||||
|
_trace_tts(text, outcome, total_bytes, locals().get('n_chunks', 0), time.time() - t0)
|
||||||
|
|
||||||
def read_body(self, limit: int = 4 * 1024 * 1024) -> bytes:
|
def read_body(self, limit: int = 4 * 1024 * 1024) -> bytes:
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user