From d531d0428167eecc562f97e762e5154631b6e726 Mon Sep 17 00:00:00 2001 From: TXyy2023 <145091426+TXyy2023@users.noreply.github.com> Date: Tue, 20 Oct 2026 10:00:20 +0800 Subject: [PATCH] fix(tts): handle retained audio files in wakeup cache (#3451) --- .../xiaozhi-server/core/handle/helloHandle.py | 13 +- .../tests/core/handle/test_wakeup_response.py | 116 ++++++++++++++++++ 2 files changed, 128 insertions(+), 1 deletion(-) create mode 100644 main/xiaozhi-server/tests/core/handle/test_wakeup_response.py diff --git a/main/xiaozhi-server/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py index 3f4a11e3b..f85301b2a 100644 --- a/main/xiaozhi-server/core/handle/helloHandle.py +++ b/main/xiaozhi-server/core/handle/helloHandle.py @@ -8,7 +8,7 @@ from typing import TYPE_CHECKING if TYPE_CHECKING: from core.connection import ConnectionHandler from core.utils.dialogue import Message -from core.utils.util import audio_to_data +from core.utils.util import audio_to_data, audio_to_data_stream from core.providers.tts.dto.dto import SentenceType from core.utils.wakeup_word import WakeupWordsConfig from core.handle.sendAudioHandle import sendAudioMessage, send_tts_message @@ -145,6 +145,17 @@ async def wakeupWordsResponse(conn: "ConnectionHandler"): if not tts_result: return + # Retained TTS audio is a file path, not a list of Opus frames. + if isinstance(tts_result, str): + opus_packets = [] + await asyncio.to_thread( + audio_to_data_stream, + tts_result, + callback=opus_packets.append, + sample_rate=conn.sample_rate, + ) + tts_result = opus_packets + # 获取当前音色 voice = getattr(conn.tts, "voice", "default") diff --git a/main/xiaozhi-server/tests/core/handle/test_wakeup_response.py b/main/xiaozhi-server/tests/core/handle/test_wakeup_response.py new file mode 100644 index 000000000..a11c44fbd --- /dev/null +++ b/main/xiaozhi-server/tests/core/handle/test_wakeup_response.py @@ -0,0 +1,116 @@ +"""Wakeup caching accepts both return forms of TTSProviderBase.to_tts.""" + +import asyncio +import math +import struct +import wave +from io import BytesIO +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + + +@pytest.fixture +def wakeup_runtime(tmp_path, monkeypatch): + # conftest supplies local configuration; no deployment config is required. + from config import settings + + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(settings, "config_file_valid", True) + from core.handle import helloHandle + from core.providers.tts.base import TTSProviderBase + from core.utils.wakeup_word import WakeupWordsConfig + + class LocalTTS(TTSProviderBase): + """Replace only remote synthesis; keep the real file and Opus conversion.""" + + def __init__(self, output_dir, delete_audio_file): + super().__init__({"output_dir": str(output_dir)}, delete_audio_file) + self.voice = "test-voice" + self.filename = output_dir / "retained.wav" + buffer = BytesIO() + with wave.open(buffer, "wb") as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(22050) + audio.writeframes( + b"".join( + struct.pack( + "= sample_rate + assert any(audio.readframes(audio.getnframes())) + if not delete_audio_file: + assert tts.filename.read_bytes() == tts.audio_bytes + assert not helloHandle._wakeup_response_lock.locked() + + +@pytest.mark.parametrize("tts_result", [None, []]) +def test_empty_synthesis_does_not_replace_cached_response(wakeup_runtime, tts_result): + helloHandle, wakeup_cache, _ = wakeup_runtime + wakeup_cache.generate_file_path = Mock() + wakeup_cache.update_wakeup_response = Mock() + conn = SimpleNamespace(tts=SimpleNamespace(to_tts=lambda _: tts_result)) + + asyncio.run(helloHandle.wakeupWordsResponse(conn)) + + wakeup_cache.generate_file_path.assert_not_called() + wakeup_cache.update_wakeup_response.assert_not_called() + assert not helloHandle._wakeup_response_lock.locked() + + +def test_missing_retained_file_preserves_cache_and_releases_lock(wakeup_runtime): + helloHandle, wakeup_cache, _ = wakeup_runtime + wakeup_cache.generate_file_path = Mock() + wakeup_cache.update_wakeup_response = Mock() + conn = SimpleNamespace( + tts=SimpleNamespace(voice="test-voice", to_tts=lambda _: "missing.wav"), + sample_rate=16000, + ) + + with pytest.raises(FileNotFoundError): + asyncio.run(helloHandle.wakeupWordsResponse(conn)) + + wakeup_cache.generate_file_path.assert_not_called() + wakeup_cache.update_wakeup_response.assert_not_called() + assert not helloHandle._wakeup_response_lock.locked()