Advertisement
About80Ninjas

Fast YT2MP3

May 2nd, 2024
509
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. import os
  2. import subprocess
  3. import time
  4. from pytube import Playlist, YouTube
  5. from multiprocessing import Pool
  6.  
  7.  
  8. def convert_youtube_video_to_mp3(args):
  9.     url, output_path = args
  10.     # create a youtube object
  11.     yt = YouTube(url)
  12.  
  13.     # get the first video stream
  14.     stream = yt.streams.get_audio_only()
  15.  
  16.     # download the video
  17.     stream.download(output_path=output_path)
  18.  
  19.     # get the file name
  20.     file_name = ''.join(c for c in yt.title if c.isalnum() or c in ' _-')  # remove invalid characters
  21.  
  22.     # create the path of the downloaded video
  23.     video_path = os.path.join(output_path, f"{file_name}.mp4")
  24.  
  25.     # convert the video to mp3
  26.     ffmpeg_path = "/usr/local/bin/ffmpeg"  # replace with the actual path to ffmpeg
  27.     mp3_path = os.path.join(output_path, f"{os.path.splitext(file_name)[0]}.mp3")
  28.     subprocess.check_call([ffmpeg_path, "-i", video_path, mp3_path])
  29.    
  30.     # remove the downloaded video
  31.     os.remove(video_path)
  32.  
  33.  
  34. def convert_youtube_playlist_to_mp3(playlist_url, output_path):
  35.     """Converts a youtube playlist into mp3 and saves them."""
  36.     # create a playlist object
  37.     playlist = Playlist(playlist_url)
  38.  
  39.     # create a multiprocessing pool
  40.     with Pool() as pool:
  41.         # map the video urls to the conversion function
  42.         pool.map(convert_youtube_video_to_mp3, [(video, output_path) for video in playlist.video_urls])
  43.         # wait for all processes to finish
  44.         pool.close()
  45.         pool.join()
  46.  
  47.  
  48. if __name__ == "__main__":
  49.     playlist_url = "https://www.youtube.com/watch?v=rmzJgQi354M&list=RDGMEMveQBJ5EaHfODz2alVFs-IQVMrmzJgQi354M"
  50.     output_path = "./downloads"
  51.     convert_youtube_playlist_to_mp3(playlist_url, output_path)
  52.  
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement