From e58551bfb548515913fe48cebc3f70d8a6c81b3b Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Sun, 23 Feb 2025 18:14:00 +0800 Subject: [PATCH] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.yaml | 16 ++++++ core/handle/audioHandle.py | 12 ---- core/handle/musicHandler.py | 75 ++++++++++++------------- music/music_config.yaml | 12 ---- music/{mp3 => }/一念千年_国风版.mp3 | Bin music/{mp3 => }/中秋月.mp3 | Bin music/{mp3 => }/廉波老矣,尚能饭否.mp3 | Bin requirements.txt | 2 +- 8 files changed, 54 insertions(+), 63 deletions(-) delete mode 100644 music/music_config.yaml rename music/{mp3 => }/一念千年_国风版.mp3 (100%) rename music/{mp3 => }/中秋月.mp3 (100%) rename music/{mp3 => }/廉波老矣,尚能饭否.mp3 (100%) diff --git a/config.yaml b/config.yaml index 6763ee545..076c70bcd 100644 --- a/config.yaml +++ b/config.yaml @@ -304,3 +304,19 @@ module_test: - "你好,请介绍一下你自己" - "What's the weather like today?" - "请用100字概括量子计算的基本原理和应用前景" + +# 本地音乐播放配置 +music: + music_commands: + - "来一首歌" + - "唱一首歌" + - "播放音乐" + - "来点音乐" + - "背景音乐" + - "放首歌" + - "播放歌曲" + - "来点背景音乐" + - "我想听歌" + - "我要听歌" + - "放点音乐" + music_dir: "./music" # 音乐文件存放路径 \ No newline at end of file diff --git a/core/handle/audioHandle.py b/core/handle/audioHandle.py index 1f85bfab1..c13918019 100644 --- a/core/handle/audioHandle.py +++ b/core/handle/audioHandle.py @@ -3,18 +3,6 @@ import json import asyncio import time from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji -import os -from pydub import AudioSegment -from pydub.playback import play -from concurrent.futures import ThreadPoolExecutor -import re -import uuid -import tempfile -import winsound # Windows专用 -import pygame -import traceback -import random -import difflib from core.handle.musicHandler import MusicHandler TAG = __name__ diff --git a/core/handle/musicHandler.py b/core/handle/musicHandler.py index c09f2431e..6ab3e77d0 100644 --- a/core/handle/musicHandler.py +++ b/core/handle/musicHandler.py @@ -9,39 +9,40 @@ import traceback import time import threading import websockets -import yaml TAG = __name__ logger = setup_logging() + class MusicHandler: def __init__(self, config): self.config = config - # 加载独立音乐配置 - music_config_path = os.path.abspath("music/music_config.yaml") - if os.path.exists(music_config_path): - with open(music_config_path, 'r') as f: - self.music_config = yaml.safe_load(f) + self.music_related_keywords = [] + + if "music" in self.config: + self.music_config = self.config["music"] + self.music_dir = os.path.abspath( + self.music_config.get("music_dir", "./music") # 默认路径修改 + ) + self.music_related_keywords = self.music_config.get("music_commands", []) else: - self.music_config = {} - logger.bind(tag=TAG).warning("未找到独立音乐配置文件,使用默认配置") - - self.music_dir = os.path.abspath( - self.music_config.get("music_dir", "./music/mp3") # 默认路径修改 - ) + self.music_dir = os.path.abspath("./music") + self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌", + "播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"] + 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) @@ -49,18 +50,17 @@ class MusicHandler: logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") await self.play_local_music(conn, specific_file=best_match) return True - + # 检查是否是通用播放音乐命令 - music_related_keywords = self.music_config.get("music_commands", []) - if any(cmd in clean_text for cmd in music_related_keywords): + if any(cmd in clean_text for cmd in self.music_related_keywords): await self.play_local_music(conn) return True - + return False def _extract_song_name(self, text): """从用户输入中提取歌名""" - for keyword in ["听", "播放", "放"]: + for keyword in ["听", "播放", "放", "唱"]: if keyword in text: parts = text.split(keyword) if len(parts) > 1: @@ -71,14 +71,13 @@ class MusicHandler: """查找最匹配的歌曲""" 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): @@ -117,18 +116,18 @@ class MusicHandler: 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()}") @@ -141,13 +140,13 @@ class MusicHandler: 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(): # 如果被中断,先发送停止消息再退出 @@ -157,22 +156,22 @@ class MusicHandler: 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("音乐播放被强制取消") @@ -184,7 +183,7 @@ class MusicHandler: """发送TTS状态消息""" if not hasattr(conn, 'websocket') or not hasattr(conn.websocket, 'send'): return - + message = { "type": "tts", "state": state, @@ -201,7 +200,7 @@ class MusicHandler: """停止音乐播放""" self.stop_event.set() self.is_playing = False - + # 增强中断可靠性 if hasattr(self, '_current_stream_task'): try: @@ -210,7 +209,7 @@ class MusicHandler: 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 + logger.bind(tag=TAG).info("音乐播放已强制终止") diff --git a/music/music_config.yaml b/music/music_config.yaml deleted file mode 100644 index 0336f8f8b..000000000 --- a/music/music_config.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# 本地音乐播放配置 -music_commands: - - "播放音乐" - - "来点音乐" - - "背景音乐" - - "放首歌" - - "播放歌曲" - - "来点背景音乐" - - "我想听歌" - - "我要听歌" - - "放点音乐" -music_dir: "./music/mp3" # 音乐文件存放路径 diff --git a/music/mp3/一念千年_国风版.mp3 b/music/一念千年_国风版.mp3 similarity index 100% rename from music/mp3/一念千年_国风版.mp3 rename to music/一念千年_国风版.mp3 diff --git a/music/mp3/中秋月.mp3 b/music/中秋月.mp3 similarity index 100% rename from music/mp3/中秋月.mp3 rename to music/中秋月.mp3 diff --git a/music/mp3/廉波老矣,尚能饭否.mp3 b/music/廉波老矣,尚能饭否.mp3 similarity index 100% rename from music/mp3/廉波老矣,尚能饭否.mp3 rename to music/廉波老矣,尚能饭否.mp3 diff --git a/requirements.txt b/requirements.txt index bfa9ed803..2ccc0584e 100755 --- a/requirements.txt +++ b/requirements.txt @@ -16,4 +16,4 @@ aiohttp_cors==0.7.0 ormsgpack==1.7.0 ruamel.yaml==0.18.10 loguru==0.7.3 -requests>=2.0.0 \ No newline at end of file +requests==2.32.3 \ No newline at end of file