Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import unicode_literals
- import youtube_dl
- from os import path, listdir, rename, mkdir
- import sys
- # sudo apt-get install ffmpeg ## Also required
- # RUN:
- # Python3 mp3_downloader.py (assumes songs.txt in the same dir with links)
- # Python3 mp3_downloader.py <file_with_links_relative_to_script>
- def get_all_links(this_dir, file_name):
- with open(path.join(this_dir, './%s' % file_name)) as f:
- return [w.rstrip() for w in f.readlines() if w.strip()]
- def all_links_valid(links):
- ydl_opts = {
- 'quiet': True,
- 'skip_download': True,
- 'format': 'bestaudio/best',
- 'postprocessors': [{
- 'key': 'FFmpegExtractAudio',
- 'preferredcodec': 'mp3',
- 'preferredquality': '320',
- }],
- }
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
- try:
- ydl.download(links)
- except:
- return False
- return True
- def download_all(links):
- ydl_opts = {
- 'format': 'bestaudio/best',
- 'postprocessors': [{
- 'key': 'FFmpegExtractAudio',
- 'preferredcodec': 'mp3',
- 'preferredquality': '320',
- }],
- }
- with youtube_dl.YoutubeDL(ydl_opts) as ydl:
- ydl.download(links)
- def get_all_file_names(this_dir, script_files):
- return {x for x in listdir(this_dir) if path.isfile(path.join(this_dir, x))} - script_files
- def new_name(old_name):
- return '-'.join(old_name.split('-')[:-1]) + '.mp3'
- def move_all_files(this_dir, script_files):
- for name in get_all_file_names(this_dir, script_files):
- rename(path.join(this_dir, name), path.join(path.join(this_dir, './output/'), new_name(name)))
- def check_folder(this_dir):
- folder = path.join(this_dir, './output/')
- if not path.exists(folder):
- mkdir(folder)
- def main(args):
- file_name = args[0] if args else 'songs.txt'
- script_files = {file_name, 'downloader.py'}
- this_dir = path.abspath(path.dirname(__file__))
- links = get_all_links(this_dir, file_name)
- if not all_links_valid(links):
- print('At least one link is invalid')
- return
- download_all(links)
- check_folder(this_dir)
- move_all_files(this_dir, script_files)
- if __name__ == '__main__':
- main(sys.argv[1:])
Add Comment
Please, Sign In to add comment