From ce58103295b5e71547310cc2f81d22befafdfd06 Mon Sep 17 00:00:00 2001 From: JISAUAY Date: Mon, 8 Sep 2025 13:03:30 -0500 Subject: [PATCH] move conn.stream to another thread --- textual1/app.py | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/textual1/app.py b/textual1/app.py index 5757a21..d177024 100644 --- a/textual1/app.py +++ b/textual1/app.py @@ -1,6 +1,7 @@ import logging import os import io +import asyncio LOG_FILE = 'textual.log' LOGGING_LEVEL = logging.DEBUG @@ -498,18 +499,19 @@ class TextualSubpyPlayer(App): audio_data = None audio_cache_path = f'.cache/audio/{song.id}.ogg' - if CACHE: - if os.path.exists(audio_cache_path): - with open(audio_cache_path, 'rb') as file: - audio_data = io.BytesIO(file.read()) + if CACHE and os.path.exists(audio_cache_path): + with open(audio_cache_path, 'rb') as file: + audio_data = io.BytesIO(file.read()) + else: + # Run the blocking stream call in a separate thread + r = await asyncio.to_thread(conn.stream, song.id) + audio_content = r.content - if not audio_data: - r = conn.stream(song.id) if CACHE: - with open(audio_cache_path, "wb") as file: - file.write(r.content) + # Also run the file writing in a thread + await asyncio.to_thread(self._cache_audio, audio_cache_path, audio_content) - audio_data = io.BytesIO(r.content) + audio_data = io.BytesIO(audio_content) pygame.mixer.music.load(audio_data) pygame.mixer.music.play() @@ -526,6 +528,11 @@ class TextualSubpyPlayer(App): # Set callback loop for progress bar # self.progress_timer = self.set_interval(1 / 10, self.update_progress, pause=False) + def _cache_audio(self, path: str, content: bytes) -> None: + """Helper method to write audio to cache.""" + with open(path, "wb") as file: + file.write(content) + def check_done_playing(self) -> None: if not pygame.mixer.music.get_busy() and not self.is_paused: self.play_history.append(self.currently_playing)