ewaldc / Spotify-Recorder

Records and encodes tracks from Spotify
2 stars 0 forks source link

Permissions missing #1

Open jan0val opened 1 year ago

jan0val commented 1 year ago

C:\Users\valec\Downloads\Spotify-Recorder-master>spotify-recorder.py --user lukas.valecek@email.cz https://open.spotify.com/track/2yPoXCs7BSIUrucMdK5PzV?si=9baa57fd39334a27 Spotify Recorder - version 1.0 Unicode support: Yes Output directory: C:\Users\valec\Downloads\Spotify-Recorder-master Settings directory: C:\Users\valec.spotify-recorder Filename Format String: {album_artist}/{album}/{artist} - {track_name}.{ext} Overwrite files: No Process priority: Priority.HIGH_PRIORITY_CLASS HTTP Error for GET to https://api.spotify.com/v1/me/player/devices with Params: {} returned 401 due to Permissions missing Traceback (most recent call last): File "C:\Users\valec\AppData\Local\Programs\Python\Python310\lib\site-packages\spotipy\client.py", line 269, in _internal_call response.raise_for_status() File "C:\Users\valec\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 1021, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://api.spotify.com/v1/me/player/devices

ewaldc commented 1 year ago

Hello Jan, Have you done this part of the install ? A Spotify developer account and premium account is required for overall operation. Take a look at: Spotify for developers for setting up your Spotify Developer account.

Once you have obtained your credentials create a ".env" file in the top folder with following content:

# Variables for Spotify Web API
SPOTIPY_CLIENT_ID="<client ID>"
SPOTIPY_CLIENT_SECRET="<client secret>"
SPOTIPY_REDIRECT_URI="http://www.purple.com/"

It does not work with --user and your email address.

jan0val commented 1 year ago

last thing i can do is this: image

then this apears: http://[localhost](http://localhost:8888/callback?code=AQBA9GNgbAkiDBtXjeoiO3HZyd-pJY3HZ6Ae-Fwi8hGoy_M9rjgi1vEV4gWUgikwqJMCzo5kH5Fm34JNncDUUGslqVGv-0FhPZTOeotgyLSQoYkTKtterCN8GTytFKvUogK-o2F6bMBNONkL9NwpmZGdXvgiAHDW8oGej3Mt93Z1rQ):8888/callback?code=AQBA9GNgbAkiDBtXjeoiO3HZyd-pJY3HZ6Ae-Fwi8hGoy_M9rjgi1vEV4gWUgikwqJMCzo5kH5Fm34JNncDUUGslqVGv-0FhPZTOeotgyLSQoYkTKtterCN8GTytFKvUogK-o2F6bMBNONkL9NwpmZGdXvgiAHDW8oGej3Mt93Z1rQ

and the error massage in cmd (401, what you can find in the last massage above)

i have tried both email and username as parameter of u but same 401 error. Do you know what is the problem? Please write down exact syntaxe for record single track with all requiered params maybe i just typed something incorrect.

ewaldc commented 1 year ago

Take a look at the examples I posted. Recording a single track is: .\spotify-recorder.exe spotify:track:52xaypL0Kjzk0ngwv3oBPR There is no need to specify any user or password. Just make sure you created the .env file with the Spotify API credentials. The very first time the code will notice that there is no cached token, so it will open a browser window with the URL, exactly as you posted. On the terminal you will notice a prompt: 'Enter the URL you were redirected to:'. Paste the whole URL into the terminal. The "code=" part of the URL is your access token. If all goes well, you will find a "%USERPROFILE%\.spotify-recorder" (e.g. "C:\users\ewald\.spotify-recorder") directory with 2 files:

EDIT: I posted an updated executable that fixes 4 issues (not related to your issue) - please update to this version Hope that helps.

jan0val commented 1 year ago

I write user because of this: image

ewaldc commented 1 year ago

Yes, I just found that out...
It may be related to a % sign in the help text that I recently introduced, That seems to corrupt argparse. But I might also have accidently deleted a comment sign. Will post a fix today and let you know. Sorry about that...

jan0val commented 1 year ago

For me, it would be better if u can post video tutorial spet by step on how to set up and use this app. There all will be much clear and shown on the example. I realy hate large dogs, because i have feeling, my head want to explode and also because I am not that good in programing.

ewaldc commented 1 year ago

Good suggestion, might do that one day.... Will also simplify the readme page and move the advanced stuff out.
The issues though were caused by a nasty undocumented behaviour in argparse which resulted in all kind of error messages. I have fixed the error and added a few extra print statements so you can see which user/email is being used. It will also tell you the things it does at first time initialization.
Please download the latest version. Apologies for the inconvenience...

Installation is really as easy as downloading the executable, installing ffmpeg and running .\spotify-recorder.exe spotify:track:52xaypL0Kjzk0ngwv3oBP to record a single track in PCM format.

jan0val commented 1 year ago

unfortunately problem has changed: image

ewaldc commented 1 year ago

Nice, no more Spotify API issues at least! This is a more typical issue. Do you have a "default" input ("recording") device and a "default" output device ? Also, set both to 2-channel 16-bit 48000Hz (you might have to change that "playback" configuration). I am in the process of creating a diagnostic test program for the audio part. With Windows 10 and 11, there is lots of stuff that can go wrong. Windows 11 made it even worse, unfortunately. Anti-virus software might also cause issues, that was the case on my neighbours system (disallowed application access to the "microphone"). I will see if I can add a --debug options that adds some more diagnostic device info.

jan0val commented 1 year ago

It works, thanks, but in the beginning you can hear clip, that is often there, for example when you have stopped progress of the song, hit prev song that nulls progress of the song and then you hit play or like in our case when you open a link, you can hear same clip in the beginning. It is a bit annoying

ewaldc commented 1 year ago

Sorry, I don't understand. Spotify-recorder controls the Spotify player on Windows to start and stop at each track. You should not have to start/stop/pause anything by yourself. Open the Spotify Windows player and do not touch it. Then you can use spotify-recorder to record a playlist. It's best not to touch the PC during recording, so you are not missing any audio samples (e.g. record overnight). It's OK to put the playback sound volume to 0, as spotify-recorder sets the internal loopback recording volume to 100%. I can not hear any clip/distortion or whatsoever on any of the recordings.

jan0val commented 1 year ago

I didnt touch anything to my PC during recording, but only when I try to open link (that is required parameter of spotify-recorder) throught my browser then after redirecting me to spotify app i can hear it before song starts.

ewaldc commented 1 year ago

That link with the "access token", you should only have to enter the very first time. After that it is cached in a file residing in `%USERPROFILE%\\.spotify-recorder. Is that not happening for you ?

jan0val commented 1 year ago

I dont need to enter anything, new tab pops up and ten closes (I deleted the file and tested it)

jan0val commented 1 year ago

what happens when token expires?

ewaldc commented 1 year ago

The code detects an expired token and uses the expired token to get a new one (token refresh). Token refresh is a different process than initial token acquisition. Originally, a had a mini web server in the code that could capture the access token from Spotify automatically, but that had other disadvantages (firewalls, port conflicts, other web servers running etc.). So I took it out.

jan0val commented 1 year ago

I tried to record multiple times, sometimes clip sound is in the beginning and also at the end, sometimes is only at the end .... It is more random issue. I know when I recorded throught audacity the problem was similar

Mmm.. so i have spotify-recorder 1.0 exe from yesterdays relesease so maybee i should download the latest python project, should i?

jan0val commented 1 year ago

Exception in thread Thread-1 (encode_and_tag): Traceback (most recent call last): File "C:\Users\Janoval\Downloads\Spotify-Recorder-master\lib\tags.py", line 305, in set_metadata_tags audio = mutagen.wave.WAVE(audio_file) ^^^^^^^^^^^^ AttributeError: module 'mutagen' has no attribute 'wave'

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "C:\Users\Janoval\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner self.run() File "C:\Users\Janoval\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 975, in run self._target(*self._args, **self._kwargs) File "C:\Users\Janoval\Downloads\Spotify-Recorder-master\lib\recorder.py", line 77, in encode_and_tag set_metadata_tags(self, output_file, idx, track_info, codec, ext) File "C:\Users\Janoval\Downloads\Spotify-Recorder-master\lib\tags.py", line 421, in set_metadata_tags except Exception as e: print(Fore.YELLOW + "Warning: exception while saving tag: " + type(e) + Fore.RESET)


TypeError: can only concatenate str (not "type") to str

Success Summary (1)
-------------------------------------------------------------------------------
 • CeeFineAss - Payback
ewaldc commented 1 year ago

I have not changed anything to the recording code. If you have the same issue with Audacity, it may be hardware related (I was going to ask you to test with Audacity anyway...). Are you sure all audio enhancements are disabled? I have done comparisons with spectral analysis of the recordings and could not identify such issue. I am using loopback audio, so the hardware isn't even used (e.g. you turn the volume down). You could even use a virtual audio device like this.

ewaldc commented 1 year ago

I added WAV metadata tagging only yesterday due to previously unsolvable defects. Hence you may want to download the latest release executable. Mutagen has it's defects, I had to work around several ones and only yesterday I got it to work for WAV across Windows 10 and 11. Can you provide the track id that produces this issue, so I can replicate ? Personally I encode to FLAC (lossless) and Opus (for mobile) and discard the raw recording. FLAC is 4x smaller without hearable loss.

jan0val commented 1 year ago

This is that cliping sound: image (I recorded manually)

jan0val commented 1 year ago

I dont know if you meant 'spotify' track id. spotify:track:0oxz0MGKupBPgrPHSt776f

jan0val commented 1 year ago

OK, so I tried to import result 'song' from your app to adudacity and then play. i found out that the problem was in the groove player but only for cliping at the end. (this time current result has no cliping sound in the begining)

ewaldc commented 1 year ago

Metadata problem for WAV files fixed, install latest executable. Your track id now tags perfectly in WAV, including clipart. The fault was on my side... You can now also use the --debug flag to get more info on devices etc. From the graph it seems clear that something is generating a click as the stream gets opened or closed. Check that audio enhancements are off and sound drivers are up to date.

jan0val commented 1 year ago

why sound input device is needed?

why setting device to 16bit 48kHz? result 'WAV' is 32bit.

ewaldc commented 1 year ago

The loopback device is always a "recording" device as you need to stream data from it (and not to it). But it is associated with your (default) playback device e.g. your speakers. Think about it like this: Windows provides a virtual "recording" device that allows you to capture the data sent to the playback device (your speakers).
It's the 48000Hz that is of importance. You have less chance of losing frames at that rate (has to do with buffering). Don't confuse with the WAV format because floating point number is (minimally) 32-bits: the audio stream is in 16 bits if you set the playback device to 16 bits. You might set it to 24-bits, but the difference can not be heard given Spotify's 320 kb/s highest quality.

jan0val commented 1 year ago

Do you know what bit-depth and sample rate is Spotify's recording and in which format? I tought Spotify uses OGG instead of MP3

ewaldc commented 1 year ago

See here. It's not 100% clearly stated. Default premium is AAC 256kbit/s (variable bit rate I believe), but there is also the very high quality for the desktop player that is equivalent to approximately 320kbit/s, but the codec is not explicitly named. Since their master data is sampled at 384kHz, it would be more logical for it to be down-sampled to 48000Hz. Windows will transform the sample rate for you anyhow, but it is easier to down-sample. I was able to compare a recording with a master audio file at 384kHz from an artist that is also on Spotify and found the 48000Hz recording to be closer to the original. Hence my preference.

jan0val commented 1 year ago

for the first time: image

when I run same link againg: image image

ewaldc commented 1 year ago

Thanks for reporting. I could not reproduce it in the debugger, it happens in the executable version only but only after 3 attempts (each time forcing new recording and encoding). I have changed the way the mutagen library is linked in and I was not able to reproduce it any longer. Mutagen is a complex library, little things that normally don't matter, can make a difference. New executable posted.

jan0val commented 1 year ago

I dont know how to write parameters: pcm 24bit 48kHz and fail-log and tags to config.ini I wrote it wrong most likely but no message.

I will be glad if you write me all parameters for all available audio formats (exact syntaxe) so that I can use them

ewaldc commented 1 year ago

Those are settings for the audio device in Windows. For the encoding process, see the manual page. These options are passed to ffmpeg and follow the ffmpeg syntax. For example to store 24-bit audio in flac format (flac format is 16 or 32 bit only)

.\spotify-recorder --codec-args "flac=-af aformat=s32:48000"

To define it in the settings file

[main]
codec-args = "flac=-af aformat=s32:48000"
jan0val commented 1 year ago

I listened it side by side carefully and I realize that the recording from your app is not sounds same as original playback from spotify. BUT I am so sorry about that there is project that captures 'downloads' original data and has other good features, so this is absolute BEAST, I only wanted to tell you about it, so you can get the best audio possible. Here is link: https://github.com/Rafiuth/Soggfy