mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge pull request #51 from Plaud-AI/feat/demo
feat: audio flow control && mock stop event
This commit is contained in:
commit
1a36f322f0
3 changed files with 39 additions and 24 deletions
|
|
@ -9,9 +9,10 @@ from core.providers.tts.dto.dto import (
|
||||||
)
|
)
|
||||||
from core.utils.textUtils import strip_emotion_tags
|
from core.utils.textUtils import strip_emotion_tags
|
||||||
from core.utils.opus import pack_opus_with_header
|
from core.utils.opus import pack_opus_with_header
|
||||||
|
from config.logger import setup_logging
|
||||||
|
|
||||||
TAG = __name__
|
TAG = __name__
|
||||||
|
logger = setup_logging()
|
||||||
|
|
||||||
async def sendAudioMessage(conn, sentenceType, audios, text, message_tag=MessageTag.NORMAL):
|
async def sendAudioMessage(conn, sentenceType, audios, text, message_tag=MessageTag.NORMAL):
|
||||||
if conn.tts.tts_audio_first_sentence:
|
if conn.tts.tts_audio_first_sentence:
|
||||||
|
|
@ -49,8 +50,10 @@ async def sendAudioMessage(conn, sentenceType, audios, text, message_tag=Message
|
||||||
# 发送结束消息(如果是最后一个文本)
|
# 发送结束消息(如果是最后一个文本)
|
||||||
# 条件1: llm_finish_task=True 且 LAST (正常结束)
|
# 条件1: llm_finish_task=True 且 LAST (正常结束)
|
||||||
# 条件2: LAST 且 MOCK (超时触发的结束)
|
# 条件2: LAST 且 MOCK (超时触发的结束)
|
||||||
if (conn.llm_finish_task and sentenceType == SentenceType.LAST) or (sentenceType == SentenceType.LAST and message_tag == MessageTag.MOCK):
|
if conn.llm_finish_task and sentenceType == SentenceType.LAST:
|
||||||
await send_tts_message(conn, "stop", None, message_tag)
|
await send_tts_message(conn, "stop", None, message_tag)
|
||||||
|
if message_tag == MessageTag.MOCK:
|
||||||
|
return
|
||||||
conn.client_is_speaking = False
|
conn.client_is_speaking = False
|
||||||
if conn.close_after_chat:
|
if conn.close_after_chat:
|
||||||
await conn.close()
|
await conn.close()
|
||||||
|
|
@ -143,13 +146,21 @@ async def sendAudio(conn, audios, frame_duration=60, message_tag=MessageTag.NORM
|
||||||
flow_control = conn.audio_flow_control
|
flow_control = conn.audio_flow_control
|
||||||
current_time = time.perf_counter()
|
current_time = time.perf_counter()
|
||||||
|
|
||||||
|
# 流控配置
|
||||||
|
pre_buffer_count = conn.config.get("tts_audio_pre_buffer_count", 8) # 预缓冲包数(约480ms)
|
||||||
|
speed_multiplier = conn.config.get("tts_audio_speed_multiplier", 1.0) # 发送速度倍率
|
||||||
|
|
||||||
if send_delay > 0:
|
if send_delay > 0:
|
||||||
# 使用固定延迟
|
# 使用固定延迟
|
||||||
await asyncio.sleep(send_delay)
|
await asyncio.sleep(send_delay)
|
||||||
|
elif flow_control["packet_count"] < pre_buffer_count:
|
||||||
|
# 预缓冲阶段:快速发送,不做延迟
|
||||||
|
pass
|
||||||
else:
|
else:
|
||||||
# 计算预期发送时间
|
# 按略快于实时的速度发送
|
||||||
|
packets_after_prebuffer = flow_control["packet_count"] - pre_buffer_count
|
||||||
expected_time = flow_control["start_time"] + (
|
expected_time = flow_control["start_time"] + (
|
||||||
flow_control["packet_count"] * frame_duration / 1000
|
packets_after_prebuffer * frame_duration / 1000 / speed_multiplier
|
||||||
)
|
)
|
||||||
delay = expected_time - current_time
|
delay = expected_time - current_time
|
||||||
if delay > 0:
|
if delay > 0:
|
||||||
|
|
@ -231,7 +242,14 @@ async def sendAudio(conn, audios, frame_duration=60, message_tag=MessageTag.NORM
|
||||||
|
|
||||||
|
|
||||||
async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL):
|
async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL):
|
||||||
"""发送 TTS 状态消息"""
|
"""发送 TTS 状态消息
|
||||||
|
|
||||||
|
Args:
|
||||||
|
conn: Connection object
|
||||||
|
state: TTS state (start, sentence_start, stop)
|
||||||
|
text: Optional text content
|
||||||
|
message_tag: Message tag for categorization
|
||||||
|
"""
|
||||||
if text is None and state == "sentence_start":
|
if text is None and state == "sentence_start":
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|
@ -260,6 +278,7 @@ async def send_tts_message(conn, state, text=None, message_tag=MessageTag.NORMAL
|
||||||
conn.clearSpeakStatus()
|
conn.clearSpeakStatus()
|
||||||
|
|
||||||
# 发送消息到客户端
|
# 发送消息到客户端
|
||||||
|
logger.bind(tag=TAG).info(f"发送TTS消息: {message}")
|
||||||
await conn.websocket.send(json.dumps(message))
|
await conn.websocket.send(json.dumps(message))
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -84,6 +84,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
# Text buffer for current session (supports both LLM and voice_opening/closing)
|
# Text buffer for current session (supports both LLM and voice_opening/closing)
|
||||||
self._session_text_buffer = []
|
self._session_text_buffer = []
|
||||||
self._first_sent = False
|
self._first_sent = False
|
||||||
|
self._last_text_time = None
|
||||||
|
|
||||||
# Check API Key
|
# Check API Key
|
||||||
model_key_msg = check_model_key("TTS", self.api_key)
|
model_key_msg = check_model_key("TTS", self.api_key)
|
||||||
|
|
@ -241,6 +242,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
loop=self.conn.loop,
|
loop=self.conn.loop,
|
||||||
)
|
)
|
||||||
future.result()
|
future.result()
|
||||||
|
self._last_text_time = time.time()
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"Failed to flush session: {e}")
|
logger.bind(tag=TAG).error(f"Failed to flush session: {e}")
|
||||||
continue
|
continue
|
||||||
|
|
@ -264,7 +266,7 @@ class TTSProvider(TTSProviderBase):
|
||||||
# 超时检测相关变量
|
# 超时检测相关变量
|
||||||
last_message_time = time.time() # 最后一次成功拉取消息的时间
|
last_message_time = time.time() # 最后一次成功拉取消息的时间
|
||||||
timeout_last_sent = False # 是否已经因为超时发送过 LAST 消息
|
timeout_last_sent = False # 是否已经因为超时发送过 LAST 消息
|
||||||
IDLE_TIMEOUT = 1.0 # 超时阈值(秒)
|
IDLE_TIMEOUT = 2.0 # 超时阈值(秒)
|
||||||
|
|
||||||
while not self.conn.stop_event.is_set():
|
while not self.conn.stop_event.is_set():
|
||||||
text = None
|
text = None
|
||||||
|
|
@ -289,30 +291,18 @@ class TTSProvider(TTSProviderBase):
|
||||||
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
logger.bind(tag=TAG).warning(f"Unknown tts_audio_message type: {type(tts_audio_message)}")
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# 成功拉取到消息,重置 timer 和 flag
|
|
||||||
# 但如果是 MOCK LAST 消息,不重置(避免无限循环)
|
|
||||||
if not (sentence_type == SentenceType.LAST and message_tag == MessageTag.MOCK):
|
|
||||||
last_message_time = time.time()
|
|
||||||
timeout_last_sent = False
|
|
||||||
except queue.Empty:
|
except queue.Empty:
|
||||||
if self.conn.stop_event.is_set():
|
if self.conn.stop_event.is_set():
|
||||||
break
|
break
|
||||||
|
|
||||||
# 超时检测:如果超过 IDLE_TIMEOUT 没有拉取到消息,放入一条 MOCK LAST 消息
|
if self._first_sent and self._last_text_time is not None and time.time() - self._last_text_time > IDLE_TIMEOUT:
|
||||||
if not timeout_last_sent and (time.time() - last_message_time) > IDLE_TIMEOUT:
|
|
||||||
logger.bind(tag=TAG).debug(
|
|
||||||
f"Audio queue idle for {IDLE_TIMEOUT}s, putting timeout LAST message"
|
|
||||||
)
|
|
||||||
# 往队列放入 MOCK LAST 消息,由正常流程处理
|
|
||||||
self.tts_audio_queue.put(TTSAudioDTO(
|
self.tts_audio_queue.put(TTSAudioDTO(
|
||||||
sentence_type=SentenceType.LAST,
|
sentence_type=SentenceType.LAST,
|
||||||
audio_data=None,
|
audio_data=None,
|
||||||
text=None,
|
text=None,
|
||||||
message_tag=MessageTag.MOCK,
|
message_tag=MessageTag.MOCK,
|
||||||
))
|
))
|
||||||
# 设置 flag,不再重复放入
|
self._last_text_time = None
|
||||||
timeout_last_sent = True
|
|
||||||
# timer 不清零,保持原值
|
|
||||||
|
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -75,11 +75,17 @@ enable_stop_tts_notify: false
|
||||||
# 说完话是否开启提示音,音效地址
|
# 说完话是否开启提示音,音效地址
|
||||||
stop_tts_notify_voice: "config/assets/tts_notify.mp3"
|
stop_tts_notify_voice: "config/assets/tts_notify.mp3"
|
||||||
|
|
||||||
# TTS音频发送延迟配置
|
# TTS Audio Send Flow Control Configuration
|
||||||
# tts_audio_send_delay: 控制音频包发送间隔
|
# tts_audio_send_delay: Control the interval of sending audio packets
|
||||||
# 0: 使用精确时间控制,严格匹配音频帧率(默认,运行时按音频帧率计算)
|
# < 0: Use exact time control, strictly match the audio frame rate (default, calculated at runtime based on audio frame rate)
|
||||||
# > 0: 使用固定延迟(毫秒)发送,例如: 60
|
# > 0: Use fixed delay (milliseconds) to send, e.g.: 60
|
||||||
tts_audio_send_delay: 0
|
tts_audio_send_delay: 0
|
||||||
|
# tts_audio_pre_buffer_count: Number of packets to send quickly at the beginning (pre-buffer phase)
|
||||||
|
# Default: 8 packets (8 * 60ms = 480ms buffer)
|
||||||
|
tts_audio_pre_buffer_count: 8
|
||||||
|
# tts_audio_speed_multiplier: Send speed multiplier after pre-buffer phase
|
||||||
|
# Default: 1.2 (20% faster than realtime to maintain buffer)
|
||||||
|
tts_audio_speed_multiplier: 1.0
|
||||||
|
|
||||||
exit_commands:
|
exit_commands:
|
||||||
- "退出"
|
- "退出"
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue