diff --git a/core/handle/musicHandler.py b/core/handle/musicHandler.py index f1eb37ed5..93283fe6d 100644 --- a/core/handle/musicHandler.py +++ b/core/handle/musicHandler.py @@ -9,18 +9,251 @@ import time from core.handle.sendAudioHandle import send_stt_message from core.utils import p3 +import urllib.request +import urllib.parse +urllib.request.socket.setdefaulttimeout(10) +import requests +import io +from threading import Thread, Event +from queue import Queue +import struct +from pydub import AudioSegment +import miniaudio +import json +import sys +import opuslib_next + TAG = __name__ logger = setup_logging() -def _extract_song_name(text): - """从用户输入中提取歌名""" - for keyword in ["听", "播放", "放", "唱"]: - if keyword in text: - parts = text.split(keyword) - if len(parts) > 1: - return parts[1].strip() - return None + +class CustomIceCastClient(miniaudio.IceCastClient): + def read(self, num_bytes: int) -> bytes: + """Read a chunk of data from the stream.""" + while len(self._buffer) < num_bytes: + time.sleep(0.1) + if self._stop_stream: + raise ValueError("Steam stoped") + with self._buffer_lock: + chunk = self._buffer[:num_bytes] + self._buffer = self._buffer[num_bytes:] + return chunk + + +class OpusStreamConverter: + @staticmethod + def search_mp3(keywords): + try: + encoded_keywords = urllib.parse.quote(keywords) + search_url = f"https://www.kumeiwp.com/index/search/data?page=1&limit=15&word={encoded_keywords}&scope=all" + + logger.bind(tag=TAG).debug(f"Searching {keywords} {search_url}") + response = requests.get(search_url) + response.raise_for_status() + + data = response.json() + if 'data' in data and len(data['data']) > 0: + for item in data['data']: + if 'file_id' in item and 'title' in item: + file_id = item['file_id'] + import re + title = item['title'] + if title.startswith(' 5: + logger.bind(tag=TAG).debug("No new frames for 5 seconds, closing stream") + self.buffer.put(None) + if self.client: + self.client.close() + break + time.sleep(0.1) + logger.bind(tag=TAG).debug("check_timeout thread ended") + #time.sleep(0.1) + #logger.bind(tag=TAG).debug_all_threads_stack() + + def stream_reader(self, url): + try: + logger.bind(tag=TAG).debug(f"stream reader with {url}") + # Start timeout checker thread + timeout_thread = Thread(target=self.check_timeout) + timeout_thread.start() + self.last_frame_time = time.time() + + self.client = CustomIceCastClient(url) + logger.bind(tag=TAG).debug("stream client created") + + + + self.stream = miniaudio.stream_any( + source=self.client, + source_format=miniaudio.FileFormat.MP3, + output_format=miniaudio.SampleFormat.SIGNED16, + nchannels=1, + sample_rate=16000, + frames_to_read=960 + ) + logger.bind(tag=TAG).debug("stream started") + frame_counter = 0 + last_frame_len = 0 + + for frames in self.stream: + self.last_frame_time = time.time() + if not len(frames): + logger.bind(tag=TAG).debug("Empty frame detected, stream might have ended") + break + + if frame_counter == 0: + self.initialize_encoder(frames) + logger.bind(tag=TAG).debug(f"Sample Rate: {self.sample_rate}") + logger.bind(tag=TAG).debug(f"Channels: {self.channels}") + logger.bind(tag=TAG).debug(f"Frame Size: {self.frame_size}") + + if not self.is_streaming: + logger.bind(tag=TAG).debug("Streaming stopped by user") + break + + # Check for stream errors or interruptions + if last_frame_len and len(frames) != last_frame_len: + logger.bind(tag=TAG).debug(f"Frame size changed: {last_frame_len} -> {len(frames)}") + + last_frame_len = len(frames) + frame_counter += 1 + self.buffer.put(frames.tobytes()) + + logger.bind(tag=TAG).debug(f"Stream ended after {frame_counter} frames") + self.buffer.put(None) + + except ConnectionError as e: + logger.bind(tag=TAG).debug(f"Connection error: {e}") + except Exception as e: + logger.bind(tag=TAG).debug(f"Error in stream reader: {e}") + finally: + logger.bind(tag=TAG).debug(f"Stream closed") + self.timeout_event.set() + try: + self.buffer.put(None) + self.client.close() + except: + pass + + def initialize_encoder(self, first_frames): + self.sample_rate = 16000 + self.channels = 1 + self.frame_size = 960 + + self.encoder = opuslib_next.Encoder( + self.sample_rate, + self.channels, + opuslib_next.APPLICATION_AUDIO + ) + + def convert(self, url, output_file): + stream_thread = Thread(target=self.stream_reader, args=(url,)) + stream_thread.start() + + try: + with open(output_file, 'wb') as opus_file: + while True: + pcm_frame = self.buffer.get() + if pcm_frame is None: + break + + # Encode PCM to Opus + if self.encoder: + opus_frame = self.encoder.encode(pcm_frame, self.frame_size) + frame_length = len(opus_frame) + opus_file.write(struct.pack(' 0: + conn.audio_play_queue.put((opus_packets, selected_music + "[end]")) + break + + # Encode PCM to Opus + if self.encoder: + opus_frame = self.encoder.encode(pcm_frame, self.frame_size) + opus_packets.append(opus_frame) + if len(opus_packets) >= 100: + if not started: + started = True + conn.audio_play_queue.put((opus_packets, selected_music + "[start]")) + else: + conn.audio_play_queue.put((opus_packets, selected_music)) + opus_packets = [] + + except Exception as e: + logger.bind(tag=TAG).debug(f"Error during streaming: {e}") + finally: + logger.bind(tag=TAG).debug("Stream stoping") + self.is_streaming = False + stream_thread.join() + logger.bind(tag=TAG).debug("Stream stoped") + + def play(self, url, conn, selected_music): + stream_thread = Thread(target=self.stream_reader, args=(url,)) + stream_thread.start() + + playing_thread = Thread(target=self.stream_player, args=(url, conn, selected_music, stream_thread)) + playing_thread.start() + + def _find_best_match(potential_song, music_files): @@ -93,7 +326,7 @@ class MusicHandler: self.scan_time = time.time() logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}") - potential_song = _extract_song_name(clean_text) + potential_song = self._extract_song_name(clean_text) if potential_song: best_match = _find_best_match(potential_song, self.music_files) if best_match: @@ -103,11 +336,24 @@ class MusicHandler: # 检查是否是通用播放音乐命令 if any(cmd in clean_text for cmd in self.music_related_keywords): - await self.play_local_music(conn) + potential_song = self._extract_song_name(clean_text) + if potential_song: + await self.play_remote_music(conn, potential_song) + else: + await self.play_local_music(conn) return True return False + def _extract_song_name(self, text): + """从用户输入中提取歌名""" + for keyword in self.music_related_keywords + ["听", "播放", "放", "唱"]: + if keyword in text: + parts = text.split(keyword) + if len(parts) > 1: + return parts[1].strip() + return None + async def play_local_music(self, conn, specific_file=None): """播放本地音乐文件""" try: @@ -137,7 +383,7 @@ class MusicHandler: if not os.path.exists(music_path): logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") return - text = f"正在播放{selected_music}" + text = f"正在本地播放{selected_music}" await send_stt_message(conn, text) conn.tts_first_text = selected_music conn.tts_last_text = selected_music @@ -151,3 +397,23 @@ class MusicHandler: except Exception as e: logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") + + async def play_remote_music(self, conn, potential_song): + try: + logger.bind(tag=TAG).debug(f"搜索并播放音乐: {potential_song}") + url, title = OpusStreamConverter.search_mp3(potential_song) + if url: + selected_music = title + text = f"正在搜索播放{selected_music}" + await send_stt_message(conn, text) + conn.tts_first_text = selected_music + "[start]" + conn.tts_last_text = selected_music + "[end]" + conn.llm_finish_task = True + converter = OpusStreamConverter() + logger.bind(tag=TAG).debug(f"Starting playing... {selected_music}") + converter.play(url, conn, selected_music) + else: + logger.bind(tag=TAG).debug("MP3 not found") + except Exception as e: + logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 2ccc0584e..d8c3bbf06 100755 --- a/requirements.txt +++ b/requirements.txt @@ -16,4 +16,5 @@ aiohttp_cors==0.7.0 ormsgpack==1.7.0 ruamel.yaml==0.18.10 loguru==0.7.3 -requests==2.32.3 \ No newline at end of file +requests==2.32.3 +miniaudio==1.61 \ No newline at end of file