Last active
July 10, 2021 14:50
-
-
Save SeanPesce/8768d59e7cccef1ef8dfe8db057e2d50 to your computer and use it in GitHub Desktop.
Script that downloads all items in an m3u playlist and merges the resulting files with ffpmpeg. Useful for downloading songs from SoundCloud, etc.
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
#!/usr/bin/env python3 | |
# Author: Sean Pesce | |
""" | |
This script downloads all items in an m3u playlist and merges the resulting files with ffpmpeg. Useful for downloading | |
songs from SoundCloud, etc. | |
This script makes a lot of assumptions, and I've only used it for SoundCloud. I can't guarantee it will work with any | |
other website. | |
Note that SoundCloud playlists expire within a few minutes, so you should run this script immediately after downloading | |
the m3u file. | |
This script requires ffmpeg to be installed on the system. | |
""" | |
import os | |
import sys | |
import time | |
import urllib.request | |
def m3u_get_urls(m3u_fpath): | |
with open(m3u_fpath, 'r') as f: | |
lines = f.readlines() | |
urls = [] | |
for l in lines: | |
if l.startswith('http'): | |
urls.append(l.strip('\r\n')) | |
return urls | |
def m3u_to_mp3(m3u_fpath, out_fpath): | |
urls = m3u_get_urls(m3u_fpath) | |
ffmpeg_cmd = 'ffmpeg -i "concat:' | |
for i in range(0, len(urls)): | |
print(f'Downloading part {i+1} of {len(urls)}') | |
urllib.request.urlretrieve(urls[i], f'{i}.mp3') | |
time.sleep(1) | |
ffmpeg_cmd += f'{i}.mp3|' | |
ffmpeg_cmd = ffmpeg_cmd[:-1] # Trim trailing pipe character | |
ffmpeg_cmd += f'" -acodec copy "{out_fpath}"' | |
print(f'\n{ffmpeg_cmd}\n') | |
retcode = os.system(ffmpeg_cmd) | |
print('Cleaning up temporary files...') | |
for i in range(0, len(urls)): | |
os.remove(f'{i}.mp3') | |
return retcode | |
if __name__ == '__main__': | |
if len(sys.argv) < 3: | |
print(f'Usage:\n {sys.argv[0]} <m3u input file> <mp3 output file>') | |
exit() | |
M3U_FPATH = sys.argv[1] | |
MP3_FPATH = sys.argv[2] | |
RETCODE = m3u_to_mp3(M3U_FPATH, MP3_FPATH) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment