update:播放音乐插件改造

This commit is contained in:
hrz 2025-03-17 02:06:38 +08:00
parent f3e7fa8a02
commit 8d0d3c0842
5 changed files with 110 additions and 106 deletions

View file

@ -30,7 +30,7 @@ class TTSException(RuntimeError):
class ConnectionHandler: class ConnectionHandler:
def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music, _memory, _intent): def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent):
self.config = config self.config = config
self.logger = setup_logging() self.logger = setup_logging()
self.auth = AuthMiddleware(config) self.auth = AuthMiddleware(config)
@ -91,7 +91,6 @@ class ConnectionHandler:
self.private_config = None self.private_config = None
self.auth_code_gen = AuthCodeGenerator.get_instance() self.auth_code_gen = AuthCodeGenerator.get_instance()
self.is_device_verified = False # 添加设备验证状态标志 self.is_device_verified = False # 添加设备验证状态标志
self.music_handler = _music
self.close_after_chat = False # 是否在聊天结束后关闭连接 self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = False self.use_function_call_mode = False
if self.config["selected_module"]["Intent"] == 'function_call': if self.config["selected_module"]["Intent"] == 'function_call':

View file

@ -1,17 +1,19 @@
from config.logger import setup_logging from config.logger import setup_logging
import os import os
import re
import time
import random import random
import difflib import difflib
import re
import traceback import traceback
from pathlib import Path from pathlib import Path
import time
from core.handle.sendAudioHandle import send_stt_message
from core.utils import p3 from core.utils import p3
from core.handle.sendAudioHandle import send_stt_message
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
MUSIC_CACHE = {}
def _extract_song_name(text): def _extract_song_name(text):
"""从用户输入中提取歌名""" """从用户输入中提取歌名"""
@ -37,105 +39,106 @@ def _find_best_match(potential_song, music_files):
return best_match return best_match
class MusicManager: def get_music_files(music_dir, music_ext):
def __init__(self, music_dir, music_ext): music_dir = Path(music_dir)
self.music_dir = Path(music_dir) music_files = []
self.music_ext = music_ext music_file_names = []
for file in music_dir.rglob("*"):
def get_music_files(self): # 判断是否是文件
music_files = [] if file.is_file():
music_file_names = [] # 获取文件扩展名
for file in self.music_dir.rglob("*"): ext = file.suffix.lower()
# 判断是否是文件 # 判断扩展名是否在列表中
if file.is_file(): if ext in music_ext:
# 获取文件扩展名 # 添加相对路径
ext = file.suffix.lower() music_files.append(str(file.relative_to(music_dir)))
# 判断扩展名是否在列表中 music_file_names.append(os.path.splitext(str(file.relative_to(music_dir)))[0])
if ext in self.music_ext: return music_files, music_file_names
# music_files.append(str(file.resolve())) # 添加绝对路径
# 添加相对路径
music_files.append(str(file.relative_to(self.music_dir)))
music_file_names.append(os.path.splitext(str(file.relative_to(self.music_dir)))[0])
return music_files, music_file_names
class MusicHandler: def initialize_music_handler(conn):
def __init__(self, config): global MUSIC_CACHE
self.config = config if MUSIC_CACHE == {}:
logger.bind(tag=TAG).info(f"实例化音乐:")
if "music" in self.config: if "music" in conn.config:
self.music_config = self.config["music"] MUSIC_CACHE["music_config"] = conn.config["music"]
self.music_dir = os.path.abspath( MUSIC_CACHE["music_dir"] = os.path.abspath(
self.music_config.get("music_dir", "./music") # 默认路径修改 MUSIC_CACHE["music_config"].get("music_dir", "./music") # 默认路径修改
) )
self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3")) MUSIC_CACHE["music_ext"] = MUSIC_CACHE["music_config"].get("music_ext", (".mp3", ".wav", ".p3"))
self.refresh_time = self.music_config.get("refresh_time", 60) MUSIC_CACHE["refresh_time"] = MUSIC_CACHE["music_config"].get("refresh_time", 60)
else: else:
self.music_dir = os.path.abspath("./music") MUSIC_CACHE["music_dir"] = os.path.abspath("./music")
self.music_ext = (".mp3", ".wav", ".p3") MUSIC_CACHE["music_ext"] = (".mp3", ".wav", ".p3")
self.refresh_time = 60 MUSIC_CACHE["refresh_time"] = 60
# 获取音乐文件列表 # 获取音乐文件列表
self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files() MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"],
self.scan_time = time.time() MUSIC_CACHE["music_ext"])
logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}") MUSIC_CACHE["scan_time"] = time.time()
return MUSIC_CACHE
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}")
# 尝试匹配具体歌名 async def handle_music_command(conn, text):
if os.path.exists(self.music_dir): initialize_music_handler(conn)
if time.time() - self.scan_time > self.refresh_time: global MUSIC_CACHE
# 刷新音乐文件列表
self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files()
self.scan_time = time.time()
logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}")
potential_song = _extract_song_name(clean_text) """处理音乐播放指令"""
if potential_song: clean_text = re.sub(r'[^\w\s]', '', text).strip()
best_match = _find_best_match(potential_song, self.music_files) logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
if best_match:
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
await self.play_local_music(conn, specific_file=best_match)
return True
# 检查是否是通用播放音乐命令
await self.play_local_music(conn)
return True
async def play_local_music(self, conn, specific_file=None): # 尝试匹配具体歌名
"""播放本地音乐文件""" if os.path.exists(MUSIC_CACHE["music_dir"]):
try: if time.time() - MUSIC_CACHE["scan_time"] > MUSIC_CACHE["refresh_time"]:
if not os.path.exists(self.music_dir): # 刷新音乐文件列表
logger.bind(tag=TAG).error(f"音乐目录不存在: {self.music_dir}") MUSIC_CACHE["music_files"], MUSIC_CACHE["music_file_names"] = get_music_files(MUSIC_CACHE["music_dir"],
MUSIC_CACHE["music_ext"])
MUSIC_CACHE["scan_time"] = time.time()
potential_song = _extract_song_name(clean_text)
if potential_song:
best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
if best_match:
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
await play_local_music(conn, specific_file=best_match)
return True
# 检查是否是通用播放音乐命令
await play_local_music(conn)
return True
async def play_local_music(conn, specific_file=None):
global MUSIC_CACHE
"""播放本地音乐文件"""
try:
if not os.path.exists(MUSIC_CACHE["music_dir"]):
logger.bind(tag=TAG).error(f"音乐目录不存在: " + MUSIC_CACHE["music_dir"])
return
# 确保路径正确性
if specific_file:
selected_music = specific_file
music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
else:
if not MUSIC_CACHE["music_files"]:
logger.bind(tag=TAG).error("未找到MP3音乐文件")
return return
selected_music = random.choice(MUSIC_CACHE["music_files"])
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
# 确保路径正确性 if not os.path.exists(music_path):
if specific_file: logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
selected_music = specific_file return
music_path = os.path.join(self.music_dir, specific_file) text = f"正在播放{selected_music}"
else: await send_stt_message(conn, text)
if not self.music_files: conn.tts_first_text_index = 0
logger.bind(tag=TAG).error("未找到MP3音乐文件") conn.tts_last_text_index = 0
return conn.llm_finish_task = True
selected_music = random.choice(self.music_files) if music_path.endswith(".p3"):
music_path = os.path.join(self.music_dir, selected_music) opus_packets, duration = p3.decode_opus_from_file(music_path)
else:
opus_packets, duration = conn.tts.audio_to_opus_data(music_path)
conn.audio_play_queue.put((opus_packets, selected_music, 0))
if not os.path.exists(music_path): except Exception as e:
logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
return logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
text = f"正在播放{selected_music}"
await send_stt_message(conn, text)
conn.tts_first_text_index = 0
conn.tts_last_text_index = 0
conn.llm_finish_task = True
if music_path.endswith(".p3"):
opus_packets, duration = p3.decode_opus_from_file(music_path)
else:
opus_packets, duration = conn.tts.audio_to_opus_data(music_path)
conn.audio_play_queue.put((opus_packets, selected_music, 0))
except Exception as e:
logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")

View file

@ -1,12 +1,13 @@
from typing import List, Dict from typing import List, Dict
from ..base import IntentProviderBase from ..base import IntentProviderBase
from core.handle.musicHandler import initialize_music_handler
from config.logger import setup_logging from config.logger import setup_logging
import re import re
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class IntentProvider(IntentProviderBase): class IntentProvider(IntentProviderBase):
def __init__(self, config): def __init__(self, config):
super().__init__(config) super().__init__(config)
@ -74,7 +75,7 @@ class IntentProvider(IntentProviderBase):
) )
return prompt return prompt
async def detect_intent(self, conn, dialogue_history: List[Dict], text:str) -> str: async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
if not self.llm: if not self.llm:
raise ValueError("LLM provider not set") raise ValueError("LLM provider not set")
@ -89,7 +90,9 @@ class IntentProvider(IntentProviderBase):
msgStr += f"User: {text}\n" msgStr += f"User: {text}\n"
user_prompt = f"当前的对话如下:\n{msgStr}" user_prompt = f"当前的对话如下:\n{msgStr}"
prompt_music = f"{self.promot}\n<start>{conn.music_handler.music_file_names}\n<end>" music_config = initialize_music_handler(conn)
music_file_names = music_config["music_file_names"]
prompt_music = f"{self.promot}\n<start>{music_file_names}\n<end>"
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 使用LLM进行意图识别 # 使用LLM进行意图识别
intent = self.llm.response_no_stream( intent = self.llm.response_no_stream(

View file

@ -2,7 +2,6 @@ import asyncio
import websockets import websockets
from config.logger import setup_logging from config.logger import setup_logging
from core.connection import ConnectionHandler from core.connection import ConnectionHandler
from core.handle.musicHandler import MusicHandler
from core.utils.util import get_local_ip from core.utils.util import get_local_ip
from core.utils import asr, vad, llm, tts, memory, intent from core.utils import asr, vad, llm, tts, memory, intent
@ -13,7 +12,7 @@ class WebSocketServer:
def __init__(self, config: dict): def __init__(self, config: dict):
self.config = config self.config = config
self.logger = setup_logging() self.logger = setup_logging()
self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent = self._create_processing_instances() self._vad, self._asr, self._llm, self._tts, self._memory, self.intent = self._create_processing_instances()
self.active_connections = set() # 添加全局连接记录 self.active_connections = set() # 添加全局连接记录
def _create_processing_instances(self): def _create_processing_instances(self):
@ -50,7 +49,6 @@ class WebSocketServer:
self.config["TTS"][self.config["selected_module"]["TTS"]], self.config["TTS"][self.config["selected_module"]["TTS"]],
self.config["delete_audio"] self.config["delete_audio"]
), ),
MusicHandler(self.config),
memory.create_instance(memory_cls_name, memory_cfg), memory.create_instance(memory_cls_name, memory_cfg),
intent.create_instance( intent.create_instance(
self.config["selected_module"]["Intent"] self.config["selected_module"]["Intent"]
@ -80,7 +78,7 @@ class WebSocketServer:
async def _handle_connection(self, websocket): async def _handle_connection(self, websocket):
"""处理新连接,每次创建独立的ConnectionHandler""" """处理新连接,每次创建独立的ConnectionHandler"""
# 创建ConnectionHandler时传入当前server实例 # 创建ConnectionHandler时传入当前server实例
handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent) handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._memory, self.intent)
self.active_connections.add(handler) self.active_connections.add(handler)
try: try:
await handler.handle_connection(websocket) await handler.handle_connection(websocket)

View file

@ -1,5 +1,6 @@
from plugins_func.register import register_function,ToolType, ActionResponse, Action from plugins_func.register import register_function,ToolType, ActionResponse, Action
from config.logger import setup_logging from config.logger import setup_logging
from core.handle.musicHandler import handle_music_command
import asyncio import asyncio
TAG = __name__ TAG = __name__
@ -36,7 +37,7 @@ def play_music(conn, song_name: str):
# 提交异步任务 # 提交异步任务
future = asyncio.run_coroutine_threadsafe( future = asyncio.run_coroutine_threadsafe(
conn.music_handler.handle_music_command(conn, music_intent), handle_music_command(conn, music_intent),
conn.loop conn.loop
) )