From 4c77e89ecd076e4cac38e56654ea06d9edb779a1 Mon Sep 17 00:00:00 2001 From: Robert Goldmann <deadlocker@gmx.de> Date: Sat, 13 Jan 2024 15:22:06 +0100 Subject: [PATCH] SpotifyRecorder: adjust sleep time according to remaining track duration --- SpotifyRecorder.py | 26 ++++++++++++-------------- 1 file changed, 12 insertions(+), 14 deletions(-) diff --git a/SpotifyRecorder.py b/SpotifyRecorder.py index 03c6b83..c481bb3 100644 --- a/SpotifyRecorder.py +++ b/SpotifyRecorder.py @@ -15,7 +15,6 @@ LOGGER = DefaultLogger().create_logger_if_not_exists('SpotifyRecorder', logForma class SpotifyRecorder: _MAX_WAIT_TIME_TRACK_STARTING_IN_S = 10 - _WAIT_TIME_TRACK_PLAYING_IN_S = 10 _WAIT_TIME_TRACK_PLAYING_SHORT_IN_S = 1 _THRESHOLD_TRACK_END_IN_MS = 5000 @@ -132,25 +131,24 @@ class SpotifyRecorder: currentPlayback = self._spotify.current_playback() if currentPlayback['is_playing']: remainingTimeInMs = trackDurationInMs - currentPlayback['progress_ms'] + remainingTimeInSeconds = remainingTimeInMs // 1000 - if remainingTimeInMs < self._THRESHOLD_TRACK_END_IN_MS: - LOGGER.debug(f'Waiting for track to end (remaining: ' - f'{self.__convert_seconds_to_duration(remainingTimeInMs // 1000)}, ' - f'sleep: {self._WAIT_TIME_TRACK_PLAYING_SHORT_IN_S}s)...') - time.sleep(self._WAIT_TIME_TRACK_PLAYING_SHORT_IN_S) - else: - LOGGER.debug(f'Waiting for track to end (remaining:' - f' {self.__convert_seconds_to_duration(remainingTimeInMs // 1000)}, ' - f'sleep: {self._WAIT_TIME_TRACK_PLAYING_IN_S}s)...') - time.sleep(self._WAIT_TIME_TRACK_PLAYING_IN_S) - continue + sleepTime = self._WAIT_TIME_TRACK_PLAYING_SHORT_IN_S + + if remainingTimeInMs > self._THRESHOLD_TRACK_END_IN_MS: + sleepTime = remainingTimeInSeconds / 2 + + LOGGER.debug(f'Waiting for track to end (remaining: ' + f'{self.__convert_seconds_to_duration(remainingTimeInSeconds)}, ' + f'sleep: {self.__convert_seconds_to_duration(sleepTime)}s)...') + time.sleep(sleepTime) else: waitDuration = int(time.time() - startTime) if waitDuration < trackDurationInSeconds: raise RuntimeError( f'Track finished too early (waited: {waitDuration}s, expected: {trackDurationInSeconds}s)') - if waitDuration > trackDurationInSeconds + self._WAIT_TIME_TRACK_PLAYING_IN_S: + if waitDuration > trackDurationInSeconds + self._WAIT_TIME_TRACK_PLAYING_SHORT_IN_S * 3: raise RuntimeError( f'Track finished too late (waited: {waitDuration}s, expected: {trackDurationInSeconds})') @@ -180,7 +178,7 @@ class SpotifyRecorder: startTime = time.time() while time.time() - startTime < self._MAX_WAIT_TIME_TRACK_STARTING_IN_S: if self._spotify.current_playback()['is_playing']: - LOGGER.debug(f'Track started playing after {time.time() - startTime}s') + LOGGER.debug(f'Track started playing after {time.time() - startTime:.1f}s') break time.sleep(1) -- GitLab