Skip to content
Snippets Groups Projects
Commit 06a719be authored by Robert Goldmann's avatar Robert Goldmann
Browse files

SpotifyRecorder: call wav to mp3 conversion, normalize volume and set mp3 tags

parent e55040e8
No related branches found
No related tags found
No related merge requests found
......@@ -8,6 +8,7 @@ from TheCodeLabs_BaseUtils.DefaultLogger import DefaultLogger
from spotipy import SpotifyOAuth, CacheFileHandler
from AudioRecorder import AudioRecorder
from Mp3Converter import Mp3Converter
LOG_FORMAT = '[%(levelname)-7s] - %(asctime)s - %(message)s'
LOGGER = DefaultLogger().create_logger_if_not_exists('SpotifyRecorder', logFormat=LOG_FORMAT)
......@@ -106,23 +107,39 @@ class SpotifyRecorder:
skippedTrackNumbers.append(indexInPlaylist)
continue
LOGGER.info(
f'>>> Recording track {index + 1}/{len(tracks)}: #{indexInPlaylist} "{track["track"]["name"]}"...')
LOGGER.info(f'>>> Recording track {index + 1}/{len(tracks)}: '
f'#{indexInPlaylist} "{track["track"]["name"]}"...')
try:
self.__stop_playback_if_playing(deviceId)
filePath = self.__determine_file_path(indexInPlaylist, track)
recorder = AudioRecorder(self._audioDeviceName, filePath)
fileName = self.__determine_file_name(indexInPlaylist, track)
filePathWav = f'{fileName}.wav'
filePathMp3 = f'{fileName}.mp3'
recorder = AudioRecorder(self._audioDeviceName, filePathWav)
with recorder.record():
self.__play_track(deviceId, track['track']['uri'])
timeWaitedForPlaying = self.__wait_for_track_playing(track['track']['id'])
self.__wait_for_track_end(track, timeWaitedForPlaying)
Mp3Converter.convert_to_mp3(filePathWav, filePathMp3)
Mp3Converter.set_mp3_tags(filePath=filePathMp3,
title=track['track']['name'],
artist=self.__join_artists(track),
album=track['track']['album']['name'])
recordedTrackNumbers.append(indexInPlaylist)
except Exception as e:
LOGGER.error(f'An error occurred while recording track "{track["track"]["name"]}"', exc_info=e)
errorTrackNumbers.append(indexInPlaylist)
self.__print_end_statistics(errorTrackNumbers, recordedTrackNumbers, skippedTrackNumbers, len(tracks))
def __join_artists(self, track) -> str:
artists = track['track']['artists']
return ' & '.join(artist['name'] for artist in artists)
def __print_end_statistics(self, errorTrackNumbers: list[int], recordedTrackNumbers: list[int],
skippedTrackNumbers: list[int], numberOfTracks: int):
LOGGER.info('### DONE ###')
LOGGER.info('>>> Skipped <<<')
......@@ -133,13 +150,12 @@ class SpotifyRecorder:
for number in errorTrackNumbers:
LOGGER.info(f'Error #{number}')
LOGGER.info(
f'### {len(tracks)} tracks, {len(recordedTrackNumbers)} recorded, {len(skippedTrackNumbers)} skipped, {len(errorTrackNumbers)} errors ###')
LOGGER.info(f'### {numberOfTracks} tracks, {len(recordedTrackNumbers)} recorded, '
f'{len(skippedTrackNumbers)} skipped, {len(errorTrackNumbers)} errors ###')
def __determine_file_path(self, index: int, track) -> str:
artists = track['track']['artists']
artists = ' & '.join(artist['name'] for artist in artists)
fileName = f'{index} - {artists} - {track["track"]["name"]}.wav'
def __determine_file_name(self, index: int, track) -> str:
artists = self.__join_artists(track)
fileName = f'{index} - {artists} - {track["track"]["name"]}'
return os.path.join(self._destinationFolder, fileName)
def __wait_for_track_end(self, track, timeWaitedForPlaying: float) -> None:
......@@ -216,7 +232,8 @@ class SpotifyRecorder:
LOGGER.debug(f'\t\tTrack started playing after {duration:.1f}s')
break
else:
raise RuntimeError(f'Wrong track started playing (actual: {currentPlayback["item"]["id"]}, expected: {expectedTrackId})')
raise RuntimeError(
f'Wrong track started playing (actual: {currentPlayback["item"]["id"]}, expected: {expectedTrackId})')
time.sleep(1)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment