About80Ninjas icon

Fast YT2MP3

About80Ninjas | PRO | 05/02/24 08:08:47 AM UTC | 0 ⭐ | 831 👁️ | Never ⏰ | []
Python |

1.7 KB

|

None

|

0 👍

/

0 👎

import os
import subprocess
import time
from pytube import Playlist, YouTube
from multiprocessing import Pool
 
 
def convert_youtube_video_to_mp3(args):
    url, output_path = args
    # create a youtube object
    yt = YouTube(url)
 
    # get the first video stream
    stream = yt.streams.get_audio_only()
 
    # download the video
    stream.download(output_path=output_path)
 
    # get the file name
    file_name = ''.join(c for c in yt.title if c.isalnum() or c in ' _-')  # remove invalid characters
 
    # create the path of the downloaded video
    video_path = os.path.join(output_path, f"{file_name}.mp4")
 
    # convert the video to mp3
    ffmpeg_path = "/usr/local/bin/ffmpeg"  # replace with the actual path to ffmpeg
    mp3_path = os.path.join(output_path, f"{os.path.splitext(file_name)[0]}.mp3")
    subprocess.check_call([ffmpeg_path, "-i", video_path, mp3_path])
    
    # remove the downloaded video
    os.remove(video_path)
 
 
def convert_youtube_playlist_to_mp3(playlist_url, output_path):
    """Converts a youtube playlist into mp3 and saves them."""
    # create a playlist object
    playlist = Playlist(playlist_url)
 
    # create a multiprocessing pool
    with Pool() as pool:
        # map the video urls to the conversion function
        pool.map(convert_youtube_video_to_mp3, [(video, output_path) for video in playlist.video_urls])
        # wait for all processes to finish
        pool.close()
        pool.join()
 
 
if __name__ == "__main__":
    playlist_url = "https://www.youtube.com/watch?v=rmzJgQi354M&list=RDGMEMveQBJ5EaHfODz2alVFs-IQVMrmzJgQi354M"
    output_path = "./downloads"
    convert_youtube_playlist_to_mp3(playlist_url, output_path)
 
 

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎