Last active
August 25, 2024 15:08
-
-
Save SirFroweey/bb1eb0492fd6c7a031d28c5da642bf24 to your computer and use it in GitHub Desktop.
Download SoundCloud Track via SoundCloud API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mechanize | |
from lxml import etree | |
import json | |
__author__ = "https://github.com/SirFroweey/" | |
class SoundCloud: | |
""" | |
Provides an minimal interface to SoundCloud API that allows you to download a downloadable track | |
given a URL to the soundcloud profile song page. | |
""" | |
HTMLParser = etree.HTMLParser() | |
def __init__(self, client_id): | |
self.client_id = client_id | |
self._build_browser() | |
def _build_browser(self): | |
self.browser = mechanize.Browser() | |
self.browser.set_handle_robots(False) | |
self.browser.set_handle_gzip(False) | |
self.browser.set_handle_redirect(True) | |
def url(self, endpoint): | |
return endpoint + "?client_id={client_id}".format(client_id=self.client_id) | |
def find_track_id(self, url): | |
response = self.browser.open(url) | |
tree = etree.parse(response, SoundCloud.HTMLParser) | |
try: | |
track_url = tree.xpath("//meta[contains(@content, 'https://w.soundcloud.com')]")[0] | |
except IndexError: | |
track_url = None | |
if track_url is not None: | |
track_id = track_url.attrib["content"].split("%2Ftracks%2F")[1].split("&")[0] | |
return track_id | |
return None | |
def get_track_info(self, track_id): | |
url = self.url( | |
"https://api.soundcloud.com/tracks/{track_id}/".format( | |
track_id=track_id | |
) | |
) | |
response = self.browser.open(url) | |
return json.loads(response.read()) | |
def download_track(self, track_id): | |
url = self.url( | |
"https://api.soundcloud.com/tracks/{track_id}/download".format( | |
track_id=track_id | |
) | |
) | |
response = self.browser.open(url) | |
return response.read() | |
def download_song(self, url): | |
track_id = self.find_track_id(url) | |
if track_id: | |
json_data = self.get_track_info(track_id) | |
if json_data["downloadable"]: | |
# download logic here | |
print "[Downloading] raw binary data." | |
print self.download_track(track_id) | |
else: | |
print "[Error] File not available for download." | |
if __name__ == "__main__": | |
CLIENT_ID = "YOUR-CLIENT-ID" # Given after applying for the SoundCloud Developer API. | |
soundcloud = SoundCloud(client_id=CLIENT_ID) | |
soundcloud.download_song("https://soundcloud.com/ysva/call-me-maybe-vs-ignition") | |
print "[Complete]" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how does this work, could you help me downloading some tracks ?