Streaming has become the main approach to listening to music nowadays. However, it's still possible to listen to music on youtube for free - so maybe we can automate downloading new and popular songs from youtube, and economize on a streaming subscription?
Getting song charts
There are many sites which track the current charts, so let's pick just one that's easy accessible and represents a mainstream "music distributor", like Spotify. There's a page dedicated for tracking Spotify charts: spotifycharts.com
They also provide a direct download of a CSV file (direct Link), which comes in handy, so we don't have to parse the page itself.
We'll start with downloading the CSV in Python:
req = urllib.request.Request('https://spotifycharts.com/regional/global/weekly/latest/download') with urllib.request.urlopen(req) as page: charts = page.read().decode('utf-8')
Searching on Youtube
Next thing is to search for the song title and artist on youtube. The cleanest way to do this would be to use the official Google Youtube API, which you could call. Downside is you'll need to register and use an API token, which we're not going to do for now.
Instead, let's just do what the search bar does and just parse what we get back:
content = urllib.request.urlopen('http://www.youtube.com/results?search_query=' + title).read().decode('utf-8') yt_link = content.split('"videoId":"').split('"')
We'll just take the first link (identified with
videoId) which, in theory, could be any video - we just rely on Youtube's algorithm to give us the right song :-)
Downloading the song
So now we have a list of current songs, let's start thinking on how to download them. Fortunately, there's a handy tool which does exactly that - we'll use youtube-dl, so first of all, we need to install that for downloading youtube videos and converting them to MP3.
On Mac this is really easy done with:
brew install youtube-dl
You might check the Installation section on the Github page for instructions on installing it on other systems.
Then we can just try downloading a song from a direct youtube link, like the following:
% youtube-dl --extract-audio --audio-format mp3 "https://www.youtube.com/watch?v=xUVz4nRmxn4" [youtube] xUVz4nRmxn4: Downloading webpage [youtube] xUVz4nRmxn4: Downloading js player c0a91787 [youtube] xUVz4nRmxn4: Downloading js player c0a91787 [download] Destination: Galantis - No Money (Official Video)-xUVz4nRmxn4.webm [download] 100% of 3.05MiB in 00:00 [ffmpeg] Destination: Galantis - No Money (Official Video)-xUVz4nRmxn4.mp3 Deleting original file Galantis - No Money (Official Video)-xUVz4nRmxn4.webm (pass -k to keep)
Works like a charm! It downloaded the video and converted it to MP3.
Putting it together
So by putting it together, we get the following file, which will download MP3s of the current Top 50 Spotify songs:
After running it, we should have a folder full of new music to enjoy:
Thanks for reading!