update:优化代码

This commit is contained in:
hrz 2025-02-23 18:14:00 +08:00
parent 45446316de
commit e58551bfb5
8 changed files with 54 additions and 63 deletions

View file

@ -304,3 +304,19 @@ module_test:
- "你好,请介绍一下你自己" - "你好,请介绍一下你自己"
- "What's the weather like today?" - "What's the weather like today?"
- "请用100字概括量子计算的基本原理和应用前景" - "请用100字概括量子计算的基本原理和应用前景"
# 本地音乐播放配置
music:
music_commands:
- "来一首歌"
- "唱一首歌"
- "播放音乐"
- "来点音乐"
- "背景音乐"
- "放首歌"
- "播放歌曲"
- "来点背景音乐"
- "我想听歌"
- "我要听歌"
- "放点音乐"
music_dir: "./music" # 音乐文件存放路径

View file

@ -3,18 +3,6 @@ import json
import asyncio import asyncio
import time import time
from core.utils.util import remove_punctuation_and_length, get_string_no_punctuation_or_emoji 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 from core.handle.musicHandler import MusicHandler
TAG = __name__ TAG = __name__

View file

@ -9,39 +9,40 @@ import traceback
import time import time
import threading import threading
import websockets import websockets
import yaml
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class MusicHandler: class MusicHandler:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
# 加载独立音乐配置 self.music_related_keywords = []
music_config_path = os.path.abspath("music/music_config.yaml")
if os.path.exists(music_config_path): if "music" in self.config:
with open(music_config_path, 'r') as f: self.music_config = self.config["music"]
self.music_config = yaml.safe_load(f) self.music_dir = os.path.abspath(
self.music_config.get("music_dir", "./music") # 默认路径修改
)
self.music_related_keywords = self.music_config.get("music_commands", [])
else: else:
self.music_config = {} self.music_dir = os.path.abspath("./music")
logger.bind(tag=TAG).warning("未找到独立音乐配置文件,使用默认配置") self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌",
"播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"]
self.music_dir = os.path.abspath(
self.music_config.get("music_dir", "./music/mp3") # 默认路径修改
)
self.is_playing = False self.is_playing = False
self.stop_event = threading.Event() self.stop_event = threading.Event()
async def handle_music_command(self, conn, text): async def handle_music_command(self, conn, text):
"""处理音乐播放指令""" """处理音乐播放指令"""
clean_text = re.sub(r'[^\w\s]', '', text).strip() clean_text = re.sub(r'[^\w\s]', '', text).strip()
logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}") logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
# 尝试匹配具体歌名 # 尝试匹配具体歌名
if os.path.exists(self.music_dir): if os.path.exists(self.music_dir):
music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')] music_files = [f for f in os.listdir(self.music_dir) if f.endswith('.mp3')]
logger.bind(tag=TAG).debug(f"找到的音乐文件: {music_files}") logger.bind(tag=TAG).debug(f"找到的音乐文件: {music_files}")
potential_song = self._extract_song_name(clean_text) potential_song = self._extract_song_name(clean_text)
if potential_song: if potential_song:
best_match = self._find_best_match(potential_song, music_files) best_match = self._find_best_match(potential_song, music_files)
@ -49,18 +50,17 @@ class MusicHandler:
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
await self.play_local_music(conn, specific_file=best_match) await self.play_local_music(conn, specific_file=best_match)
return True return True
# 检查是否是通用播放音乐命令 # 检查是否是通用播放音乐命令
music_related_keywords = self.music_config.get("music_commands", []) if any(cmd in clean_text for cmd in self.music_related_keywords):
if any(cmd in clean_text for cmd in music_related_keywords):
await self.play_local_music(conn) await self.play_local_music(conn)
return True return True
return False return False
def _extract_song_name(self, text): def _extract_song_name(self, text):
"""从用户输入中提取歌名""" """从用户输入中提取歌名"""
for keyword in ["听", "播放", "放"]: for keyword in ["听", "播放", "放", "唱"]:
if keyword in text: if keyword in text:
parts = text.split(keyword) parts = text.split(keyword)
if len(parts) > 1: if len(parts) > 1:
@ -71,14 +71,13 @@ class MusicHandler:
"""查找最匹配的歌曲""" """查找最匹配的歌曲"""
best_match = None best_match = None
highest_ratio = 0 highest_ratio = 0
for music_file in music_files: for music_file in music_files:
song_name = os.path.splitext(music_file)[0] song_name = os.path.splitext(music_file)[0]
ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio() ratio = difflib.SequenceMatcher(None, potential_song, song_name).ratio()
if ratio > highest_ratio and ratio > 0.4: if ratio > highest_ratio and ratio > 0.4:
highest_ratio = ratio highest_ratio = ratio
best_match = music_file best_match = music_file
return best_match return best_match
async def play_local_music(self, conn, specific_file=None): 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', '')}") await self._send_tts_message(conn, "sentence_start", f"正在播放:{selected_music.replace('.mp3', '')}")
conn.is_playing_music = True conn.is_playing_music = True
# 转换并发送音频数据 # 转换并发送音频数据
opus_packets, duration = conn.tts.wav_to_opus_data(music_path) opus_packets, duration = conn.tts.wav_to_opus_data(music_path)
packet_duration = (duration * 1000) / len(opus_packets) packet_duration = (duration * 1000) / len(opus_packets)
await self._send_tts_message(conn, "sentence_end") await self._send_tts_message(conn, "sentence_end")
await self._send_tts_message(conn, "sentence_start", selected_music) await self._send_tts_message(conn, "sentence_start", selected_music)
await self._stream_audio_packets(conn, opus_packets, packet_duration) await self._stream_audio_packets(conn, opus_packets, packet_duration)
await self._send_tts_message(conn, "sentence_end") await self._send_tts_message(conn, "sentence_end")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"音乐流发送失败: {str(e)}") logger.bind(tag=TAG).error(f"音乐流发送失败: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
@ -141,13 +140,13 @@ class MusicHandler:
self.is_playing = True self.is_playing = True
self.stop_event.clear() self.stop_event.clear()
self.current_opus_packets = opus_packets # 存储当前数据包 self.current_opus_packets = opus_packets # 存储当前数据包
try: try:
# 将流式任务保存为实例属性 # 将流式任务保存为实例属性
self._current_stream_task = asyncio.current_task() self._current_stream_task = asyncio.current_task()
total_sent = 0 total_sent = 0
start_time = time.time() start_time = time.time()
for i, opus_packet in enumerate(opus_packets): for i, opus_packet in enumerate(opus_packets):
if self.stop_event.is_set(): if self.stop_event.is_set():
# 如果被中断,先发送停止消息再退出 # 如果被中断,先发送停止消息再退出
@ -157,22 +156,22 @@ class MusicHandler:
except: except:
pass pass
break break
expected_time = start_time + (i * packet_duration / 1000) expected_time = start_time + (i * packet_duration / 1000)
current_time = time.time() current_time = time.time()
if current_time < expected_time: if current_time < expected_time:
await asyncio.sleep(expected_time - current_time) await asyncio.sleep(expected_time - current_time)
try: try:
await conn.websocket.send(opus_packet) await conn.websocket.send(opus_packet)
total_sent += len(opus_packet) total_sent += len(opus_packet)
except: except:
break break
if i % 100 == 0: if i % 100 == 0:
logger.bind(tag=TAG).debug(f"已发送 {i}/{len(opus_packets)} 个数据包") logger.bind(tag=TAG).debug(f"已发送 {i}/{len(opus_packets)} 个数据包")
await asyncio.sleep(0.02) # 控制发送频率 await asyncio.sleep(0.02) # 控制发送频率
except asyncio.CancelledError: except asyncio.CancelledError:
logger.bind(tag=TAG).info("音乐播放被强制取消") logger.bind(tag=TAG).info("音乐播放被强制取消")
@ -184,7 +183,7 @@ class MusicHandler:
"""发送TTS状态消息""" """发送TTS状态消息"""
if not hasattr(conn, 'websocket') or not hasattr(conn.websocket, 'send'): if not hasattr(conn, 'websocket') or not hasattr(conn.websocket, 'send'):
return return
message = { message = {
"type": "tts", "type": "tts",
"state": state, "state": state,
@ -201,7 +200,7 @@ class MusicHandler:
"""停止音乐播放""" """停止音乐播放"""
self.stop_event.set() self.stop_event.set()
self.is_playing = False self.is_playing = False
# 增强中断可靠性 # 增强中断可靠性
if hasattr(self, '_current_stream_task'): if hasattr(self, '_current_stream_task'):
try: try:
@ -210,7 +209,7 @@ class MusicHandler:
logger.bind(tag=TAG).debug("成功取消流式任务") logger.bind(tag=TAG).debug("成功取消流式任务")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"取消流式任务失败: {str(e)}") logger.bind(tag=TAG).error(f"取消流式任务失败: {str(e)}")
# 清空播放队列并重置状态 # 清空播放队列并重置状态
self.current_opus_packets = [] self.current_opus_packets = []
logger.bind(tag=TAG).info("音乐播放已强制终止") logger.bind(tag=TAG).info("音乐播放已强制终止")

View file

@ -1,12 +0,0 @@
# 本地音乐播放配置
music_commands:
- "播放音乐"
- "来点音乐"
- "背景音乐"
- "放首歌"
- "播放歌曲"
- "来点背景音乐"
- "我想听歌"
- "我要听歌"
- "放点音乐"
music_dir: "./music/mp3" # 音乐文件存放路径

View file

@ -16,4 +16,4 @@ aiohttp_cors==0.7.0
ormsgpack==1.7.0 ormsgpack==1.7.0
ruamel.yaml==0.18.10 ruamel.yaml==0.18.10
loguru==0.7.3 loguru==0.7.3
requests>=2.0.0 requests==2.32.3