From 9b062917156dd9f8da8d1f4f1fc175f83a450512 Mon Sep 17 00:00:00 2001
From: Robert Goldmann <deadlocker@gmx.de>
Date: Sat, 13 Jan 2024 15:36:45 +0100
Subject: [PATCH] SpotifyRecorder: improved final duration check

---
 SpotifyRecorder.py | 21 +++++++++++++--------
 1 file changed, 13 insertions(+), 8 deletions(-)

diff --git a/SpotifyRecorder.py b/SpotifyRecorder.py
index c481bb3..a9d5f31 100644
--- a/SpotifyRecorder.py
+++ b/SpotifyRecorder.py
@@ -103,8 +103,8 @@ class SpotifyRecorder:
                 recorder = SpotifyAudioRecorder(self._audioDeviceName, filePath)
                 with recorder.record():
                     self.__play_track(deviceId, track['track']['uri'])
-                    self.__wait_for_track_playing()
-                    self.__wait_for_track_end(track)
+                    timeWaitedForPlaying = self.__wait_for_track_playing()
+                    self.__wait_for_track_end(track, timeWaitedForPlaying)
 
                 recordedTracks.append(track['track']['name'])
             except Exception as e:
@@ -120,7 +120,7 @@ class SpotifyRecorder:
         fileName = f'{index} - {artists} - {track["track"]["name"]}.wav'
         return os.path.join(self._destinationFolder, fileName)
 
-    def __wait_for_track_end(self, track):
+    def __wait_for_track_end(self, track, timeWaitedForPlaying: float) -> None:
         trackDurationInMs = track['track']['duration_ms']
         trackDurationInSeconds = trackDurationInMs // 1000
         LOGGER.info(f'Track duration: {self.__convert_seconds_to_duration(trackDurationInSeconds)}')
@@ -140,19 +140,20 @@ class SpotifyRecorder:
 
                 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)...')
+                             f'sleep: {self.__convert_seconds_to_duration(int(sleepTime))}s)...')
                 time.sleep(sleepTime)
             else:
                 waitDuration = int(time.time() - startTime)
+                waitDuration += timeWaitedForPlaying
 
-                if waitDuration < trackDurationInSeconds:
+                if waitDuration < trackDurationInSeconds - self._WAIT_TIME_TRACK_PLAYING_SHORT_IN_S:
                     raise RuntimeError(
                         f'Track finished too early (waited: {waitDuration}s, expected: {trackDurationInSeconds}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})')
 
-                LOGGER.debug(f'Track finished. Waited {waitDuration}s, expected {trackDurationInSeconds}s, OK')
+                LOGGER.info(f'Track finished. Waited {waitDuration}s, expected {trackDurationInSeconds}s, OK')
                 break
 
     @staticmethod
@@ -173,16 +174,20 @@ class SpotifyRecorder:
     def __play_track(self, deviceId: str, trackUri: str):
         self._spotify.start_playback(device_id=deviceId, uris=[trackUri])
 
-    def __wait_for_track_playing(self) -> None:
+    def __wait_for_track_playing(self) -> float:
         LOGGER.debug(f'Wait for track to start playing...')
         startTime = time.time()
+        duration = 0
         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:.1f}s')
+                duration = time.time() - startTime
+                LOGGER.debug(f'Track started playing after {duration:.1f}s')
                 break
 
             time.sleep(1)
 
+        return duration
+
 
 if __name__ == '__main__':
     with open('config/settings-recorder.json', 'r', encoding='utf-8') as f:
-- 
GitLab