This nifty little script in Python3 allows you to download a single link or a playlist and converts it to mp3.
If you don’t have python get it via the link below. Make sure to import the needed libraries using pip (pip3).
import os
import re
import moviepy.editor as mp
from pytube import YouTube, Playlist
def clean_title(title):
# Remove non-alphanumeric characters and spaces from the title
cleaned_title = re.sub(r'[^\w\s]', '', title)
return cleaned_title
def download_and_convert_to_mp3(url, output_path=None):
try:
# Download the video in the highest resolution available
yt = YouTube(url)
video = yt.streams.get_highest_resolution()
video.download(output_path=output_path)
# Get the video file path
video_file_path = os.path.join(output_path, video.default_filename)
# Clean the video title before converting to mp3
cleaned_title = clean_title(yt.title)
# Convert the video to mp3
mp3_output_path = os.path.join(output_path, f"{cleaned_title}.mp3")
clip = mp.AudioFileClip(video_file_path)
clip.write_audiofile(mp3_output_path)
# Delete the original video file
os.remove(video_file_path)
print(f"Video downloaded and converted to MP3: {mp3_output_path}")
except Exception as e:
print(f"Error downloading or converting the video: {e}")
if __name__ == "__main__":
url = input("Enter the URL of the YouTube video or playlist: ")
output_path = input("Enter the output directory (leave empty for the current directory): ")
if not output_path:
output_path = os.getcwd()
if "/playlist?list=" in url:
# Download and convert the entire playlist
playlist = Playlist(url)
for video_url in playlist.video_urls:
download_and_convert_to_mp3(video_url, output_path)
else:
# Download and convert a single video
download_and_convert_to_mp3(url, output_path)
Add comment