diff --git a/config.yaml b/config.yaml index a0ce2e1b4..2f04b4691 100644 --- a/config.yaml +++ b/config.yaml @@ -285,3 +285,22 @@ module_test: - "你好,请介绍一下你自己" - "What's the weather like today?" - "请用100字概括量子计算的基本原理和应用前景" + +# 本地音乐播放配置 +music_commands: +#下方可自定义播放音乐指令,也可直接说出想要播放的歌曲名称 + - "播放音乐" + - "来点音乐" + - "背景音乐" + - "放首歌" + - "播放歌曲" + - "来点背景音乐" + - "我想听歌" + - "我要听歌" + - "放点音乐" + - "播放歌曲" + - "播放音乐" + - "来点音乐" + - "背景音乐" + - "放首歌" +music_dir: "./music" # 将音乐文件存放在此目录 diff --git a/core/connection.py b/core/connection.py index 83251eebb..2c4794d7f 100644 --- a/core/connection.py +++ b/core/connection.py @@ -18,11 +18,12 @@ from core.handle.audioHandle import handleAudioMessage, sendAudioMessage from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError from core.utils.auth_code_gen import AuthCodeGenerator # 添加导入 +from core.handle.musicHandler import MusicHandler # 添加这行 TAG = __name__ class ConnectionHandler: - def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts): + def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, websocket_server=None): self.config = config self.logger = setup_logging() self.auth = AuthMiddleware(config) @@ -81,6 +82,8 @@ class ConnectionHandler: self.private_config = None self.auth_code_gen = AuthCodeGenerator.get_instance() self.is_device_verified = False # 添加设备验证状态标志 + self.music_handler = MusicHandler(config) # 确保这行存在 + self.websocket_server = websocket_server # 添加server引用 async def handle_connection(self, ws): @@ -316,11 +319,21 @@ class ConnectionHandler: async def close(self): """资源清理方法""" + # 先停止音乐播放 + if self.music_handler.is_playing: + self.music_handler.stop_playing() + await self.music_handler._send_tts_message(self, "stop") + + # 清理其他资源 self.stop_event.set() self.executor.shutdown(wait=False) if self.websocket: await self.websocket.close() self.logger.bind(tag=TAG).info("连接资源已释放") + + # 确保从活跃连接集合中移除 + if self.websocket_server and self in self.websocket_server.active_connections: + self.websocket_server.active_connections.discard(self) def reset_vad_states(self): self.client_audio_buffer = bytes() diff --git a/core/handle/abortHandle.py b/core/handle/abortHandle.py index 12d10ce49..46d2c5927 100644 --- a/core/handle/abortHandle.py +++ b/core/handle/abortHandle.py @@ -9,6 +9,9 @@ async def handleAbortMessage(conn): logger.bind(tag=TAG).info("Abort message received") # 设置成打断状态,会自动打断llm、tts任务 conn.client_abort = True + # 停止音乐播放 + if conn.music_handler.is_playing: + conn.music_handler.stop_playing() # 打断屏显任务 conn.stop_all_tasks() # 打断客户端说话状态 diff --git a/core/handle/audioHandle.py b/core/handle/audioHandle.py index d6ef98cde..2b9d40996 100644 --- a/core/handle/audioHandle.py +++ b/core/handle/audioHandle.py @@ -15,11 +15,17 @@ import pygame import traceback import random import difflib +from core.handle.musicHandler import MusicHandler TAG = __name__ logger = setup_logging() +class AudioHandler: + def __init__(self, config): + self.music_handler = MusicHandler(config) + + async def handleAudioMessage(conn, audio): if not conn.asr_server_receive: logger.bind(tag=TAG).debug(f"前期数据处理中,暂停接收") @@ -45,7 +51,7 @@ async def handleAudioMessage(conn, audio): text_len, text_without_punctuation = remove_punctuation_and_length(text) # 添加音乐命令处理 - if await handleMusicCommand(conn, text_without_punctuation): + if await conn.music_handler.handle_music_command(conn, text_without_punctuation): conn.asr_server_receive = True conn.asr_audio.clear() return @@ -181,173 +187,3 @@ async def no_voice_close_connect(conn): conn.asr_server_receive = False prompt = "时间过得真快,我都好久没说话了。请你用十个字左右话跟我告别,以“再见”或“拜拜”为结尾" await startToChat(conn, prompt) - - -async def play_local_music(conn, specific_file=None): - """通过websocket发送音乐到端侧设备播放""" - try: - music_dir = os.path.abspath(conn.config.get("music_dir", "./music")) - logger.bind(tag=TAG).info(f"音乐目录路径: {music_dir}") - - if not os.path.exists(music_dir): - logger.bind(tag=TAG).error(f"音乐目录不存在: {music_dir}") - return - - if specific_file: - music_path = os.path.join(music_dir, specific_file) - if not os.path.exists(music_path): - logger.bind(tag=TAG).error(f"指定的音乐文件不存在: {music_path}") - return - selected_music = specific_file - else: - music_files = [f for f in os.listdir(music_dir) if f.endswith('.mp3')] - if not music_files: - logger.bind(tag=TAG).error("未找到MP3音乐文件") - return - selected_music = random.choice(music_files) - music_path = os.path.join(music_dir, selected_music) - - logger.bind(tag=TAG).info(f"准备播放: {selected_music}") - - # 发送TTS start消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "start", - "session_id": conn.session_id - })) - - # 发送sentence_start消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "sentence_start", - "text": f"正在播放:{selected_music.replace('.mp3', '')}", - "session_id": conn.session_id - })) - - conn.is_playing_music = True - - try: - logger.bind(tag=TAG).debug("开始转换音乐文件为opus格式") - opus_packets, duration = conn.tts.wav_to_opus_data(music_path) - logger.bind(tag=TAG).info(f"转换完成,获得 {len(opus_packets)} 个数据包,时长 {duration} 秒") - - # 发送sentence_end消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "sentence_end", - "session_id": conn.session_id - })) - - # 发送新的sentence_start消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "sentence_start", - "text": selected_music, - "session_id": conn.session_id - })) - - # 计算每个数据包的播放时间(毫秒) - packet_duration = (duration * 1000) / len(opus_packets) # 每个包的持续时间(毫秒) - logger.bind(tag=TAG).info(f"每个数据包的播放时间: {packet_duration:.2f}ms") - - total_sent = 0 - start_time = time.time() - - for i, opus_packet in enumerate(opus_packets): - if not conn.is_playing_music: - break - - # 计算应该经过的时间 - expected_time = start_time + (i * packet_duration / 1000) - current_time = time.time() - - # 如果发送太快,等待一下 - if current_time < expected_time: - await asyncio.sleep(expected_time - current_time) - - await conn.websocket.send(opus_packet) - total_sent += len(opus_packet) - - # 每100个包记录一次进度 - if i % 100 == 0: - logger.bind(tag=TAG).debug(f"已发送 {i}/{len(opus_packets)} 个数据包") - - logger.bind(tag=TAG).info(f"音乐数据发送完成,共发送 {total_sent} 字节") - - # 发送sentence_end消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "sentence_end", - "session_id": conn.session_id - })) - - except Exception as e: - logger.bind(tag=TAG).error(f"音乐转换或发送失败: {str(e)}") - import traceback - logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") - - except Exception as e: - logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") - import traceback - logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") - finally: - conn.is_playing_music = False - # 发送TTS stop消息 - await conn.websocket.send(json.dumps({ - "type": "tts", - "state": "stop", - "session_id": conn.session_id - })) - - -async def handleMusicCommand(conn, text): - """处理音乐播放指令(增强版)""" - # 去除所有标点符号和空格 - clean_text = re.sub(r'[^\w\s]', '', text).strip() - - logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") - - # 1. 尝试匹配具体歌名 - music_dir = os.path.abspath(conn.config.get("music_dir", "./music")) - logger.bind(tag=TAG).debug(f"音乐目录: {music_dir}") - - if os.path.exists(music_dir): - music_files = [f for f in os.listdir(music_dir) if f.endswith('.mp3')] - logger.bind(tag=TAG).debug(f"找到的音乐文件: {music_files}") - - # 从用户输入中提取可能的歌名 - potential_song = None - for keyword in ["听", "播放", "放"]: - if keyword in clean_text: - parts = clean_text.split(keyword) - if len(parts) > 1: - potential_song = parts[1].strip() - break - - if potential_song: - # 使用模糊匹配找到最匹配的歌曲 - best_match = None - highest_ratio = 0 - - for music_file in music_files: - song_name = os.path.splitext(music_file)[0] - # 计算相似度 - ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() - if ratio > highest_ratio and ratio > 0.4: # 设置最小匹配阈值 - highest_ratio = ratio - best_match = music_file - - if best_match: - logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match} (匹配度: {highest_ratio})") - await play_local_music(conn, specific_file=best_match) - return True - else: - logger.bind(tag=TAG).info(f"未找到匹配的歌曲: {potential_song}") - - # 2. 检查是否是通用播放音乐命令 - music_related_keywords = conn.config.get("music_commands", []) - if any(cmd in clean_text for cmd in music_related_keywords): - await play_local_music(conn) - return True - - return False diff --git a/core/handle/musicHandler.py b/core/handle/musicHandler.py new file mode 100644 index 000000000..5933f8572 --- /dev/null +++ b/core/handle/musicHandler.py @@ -0,0 +1,203 @@ +from config.logger import setup_logging +import json +import asyncio +import os +import random +import difflib +import re +import traceback +import time +import threading +import websockets + +TAG = __name__ +logger = setup_logging() + +class MusicHandler: + def __init__(self, config): + self.config = config + self.music_dir = os.path.abspath(config.get("music_dir", "./music")) + self.is_playing = False + self.stop_event = threading.Event() + + async def handle_music_command(self, conn, text): + """处理音乐播放指令""" + clean_text = re.sub(r'[^\w\s]', '', text).strip() + logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") + + # 尝试匹配具体歌名 + if os.path.exists(self.music_dir): + music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')] + logger.bind(tag=TAG).debug(f"找到的音乐文件: {music_files}") + + potential_song = self._extract_song_name(clean_text) + if potential_song: + best_match = self._find_best_match(potential_song, music_files) + if best_match: + logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") + await self.play_local_music(conn, specific_file=best_match) + return True + + # 检查是否是通用播放音乐命令 + music_related_keywords = self.config.get("music_commands", []) + if any(cmd in clean_text for cmd in music_related_keywords): + await self.play_local_music(conn) + return True + + return False + + def _extract_song_name(self, text): + """从用户输入中提取歌名""" + for keyword in ["听", "播放", "放"]: + if keyword in text: + parts = text.split(keyword) + if len(parts) > 1: + return parts[1].strip() + return None + + def _find_best_match(self, potential_song, music_files): + """查找最匹配的歌曲""" + best_match = None + highest_ratio = 0 + + for music_file in music_files: + song_name = os.path.splitext(music_file)[0] + ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() + if ratio > highest_ratio and ratio > 0.4: + highest_ratio = ratio + best_match = music_file + + return best_match + + async def play_local_music(self, conn, specific_file=None): + """播放本地音乐文件""" + try: + if not os.path.exists(self.music_dir): + logger.bind(tag=TAG).error(f"音乐目录不存在: {self.music_dir}") + return + + if specific_file: + music_path = os.path.join(self.music_dir, specific_file) + if not os.path.exists(music_path): + logger.bind(tag=TAG).error(f"指定的音乐文件不存在: {music_path}") + return + selected_music = specific_file + else: + music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')] + if not music_files: + logger.bind(tag=TAG).error("未找到MP3音乐文件") + return + selected_music = random.choice(music_files) + music_path = os.path.join(self.music_dir, selected_music) + + await self._send_music_stream(conn, music_path, selected_music) + + except Exception as e: + logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + + async def _send_music_stream(self, conn, music_path, selected_music): + """播放音乐流""" + try: + # 发送开始消息 + await self._send_tts_message(conn, "start") + await self._send_tts_message(conn, "sentence_start", f"正在播放:{selected_music.replace('.mp3', '')}") + + conn.is_playing_music = True + + # 转换并发送音频数据 + opus_packets, duration = conn.tts.wav_to_opus_data(music_path) + packet_duration = (duration * 1000) / len(opus_packets) + + await self._send_tts_message(conn, "sentence_end") + await self._send_tts_message(conn, "sentence_start", selected_music) + + await self._stream_audio_packets(conn, opus_packets, packet_duration) + + await self._send_tts_message(conn, "sentence_end") + + except Exception as e: + logger.bind(tag=TAG).error(f"音乐流发送失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + finally: + conn.is_playing_music = False + await self._send_tts_message(conn, "stop") + + async def _stream_audio_packets(self, conn, opus_packets, packet_duration): + """流式发送音频数据包""" + self.is_playing = True + self.stop_event.clear() + self.current_opus_packets = opus_packets # 存储当前数据包 + + try: + # 将流式任务保存为实例属性 + self._current_stream_task = asyncio.current_task() + total_sent = 0 + start_time = time.time() + + for i, opus_packet in enumerate(opus_packets): + if self.stop_event.is_set(): + # 如果被中断,先发送停止消息再退出 + if hasattr(conn, 'websocket') and hasattr(conn.websocket, 'send'): + try: + await self._send_tts_message(conn, "stop") + except: + pass + break + + expected_time = start_time + (i * packet_duration / 1000) + current_time = time.time() + + if current_time < expected_time: + await asyncio.sleep(expected_time - current_time) + + try: + await conn.websocket.send(opus_packet) + total_sent += len(opus_packet) + except: + break + + if i % 100 == 0: + logger.bind(tag=TAG).debug(f"已发送 {i}/{len(opus_packets)} 个数据包") + + await asyncio.sleep(0.02) # 控制发送频率 + except asyncio.CancelledError: + logger.bind(tag=TAG).info("音乐播放被强制取消") + finally: + self.is_playing = False + # 移除finally块中的停止消息发送,因为已经在中断时发送过了 + + async def _send_tts_message(self, conn, state, text=None): + """发送TTS状态消息""" + if not hasattr(conn, 'websocket') or not hasattr(conn.websocket, 'send'): + return + + message = { + "type": "tts", + "state": state, + "session_id": conn.session_id + } + if text is not None: + message["text"] = text + try: + await conn.websocket.send(json.dumps(message)) + except (websockets.exceptions.ConnectionClosed, ConnectionError): + logger.bind(tag=TAG).warning("发送TTS消息时连接已关闭") + + def stop_playing(self): + """停止当前音乐播放""" + self.stop_event.set() + self.is_playing = False + + # 增强中断可靠性 + if hasattr(self, '_current_stream_task'): + try: + if not self._current_stream_task.done(): + self._current_stream_task.cancel() + logger.bind(tag=TAG).debug("成功取消流式任务") + except Exception as e: + logger.bind(tag=TAG).error(f"取消流式任务失败: {str(e)}") + + # 清空播放队列并重置状态 + self.current_opus_packets = [] + logger.bind(tag=TAG).info("音乐播放已强制终止") \ No newline at end of file diff --git a/core/handle/textHandle.py b/core/handle/textHandle.py index 9a6faaf04..8a975ab56 100644 --- a/core/handle/textHandle.py +++ b/core/handle/textHandle.py @@ -25,6 +25,16 @@ async def handleTextMessage(conn, message): conn.client_listen_mode = msg_json["mode"] logger.bind(tag=TAG).debug(f"客户端拾音模式:{conn.client_listen_mode}") if msg_json["state"] == "start": + if conn.music_handler.is_playing: + conn.music_handler.stop_playing() + await conn.websocket.send(json.dumps({ + "type": "tts", + "state": "stop", + "session_id": conn.session_id + })) + conn.clearSpeakStatus() + conn.asr_audio.clear() + conn.asr_server_receive = True conn.client_have_voice = True conn.client_voice_stop = False elif msg_json["state"] == "stop": diff --git a/core/websocket_server.py b/core/websocket_server.py index d8dce04d8..528e511bb 100644 --- a/core/websocket_server.py +++ b/core/websocket_server.py @@ -12,6 +12,7 @@ class WebSocketServer: self.config = config self.logger = setup_logging() self._vad, self._asr, self._llm, self._tts = self._create_processing_instances() + self.active_connections = set() # 添加全局连接记录 def _create_processing_instances(self): """创建处理模块实例""" @@ -58,5 +59,18 @@ class WebSocketServer: async def _handle_connection(self, websocket): """处理新连接,每次创建独立的ConnectionHandler""" - handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts) - await handler.handle_connection(websocket) + # 当有新连接时,停止所有正在播放的音乐 + for handler in self.active_connections.copy(): + if handler.music_handler.is_playing: + self.logger.bind(tag=TAG).info(f"终止现有连接 {handler.session_id} 的音乐播放") + # 先发送停止消息再终止 + await handler.music_handler._send_tts_message(handler, "stop") + handler.music_handler.stop_playing() + + # 创建ConnectionHandler时传入当前server实例 + handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self) + self.active_connections.add(handler) + try: + await handler.handle_connection(websocket) + finally: + self.active_connections.discard(handler) diff --git a/music/一念千年_国风版.mp3 b/music/一念千年_国风版.mp3 new file mode 100644 index 000000000..31801be18 Binary files /dev/null and b/music/一念千年_国风版.mp3 differ diff --git a/music/中秋月.mp3 b/music/中秋月.mp3 new file mode 100644 index 000000000..abde29120 Binary files /dev/null and b/music/中秋月.mp3 differ diff --git a/music/月亮代表我的心_邓丽君.mp3 b/music/月亮代表我的心_邓丽君.mp3 deleted file mode 100644 index 1ec072f5d..000000000 Binary files a/music/月亮代表我的心_邓丽君.mp3 and /dev/null differ diff --git a/music/踏山河.mp3 b/music/踏山河.mp3 deleted file mode 100644 index 3edb6cccf..000000000 Binary files a/music/踏山河.mp3 and /dev/null differ