import os import yt_dlp import vlc import time import eyed3 def download_and_play(url): video_id = url.split('=')[1][:11] # Extract the video ID from the YouTube URL output_path = os.path.expanduser(f'/home/generalized/Music/{video_id}.mp3') # Path where the file will be saved if not os.path.exists(output_path): print("Downloading...") # Configure yt-dlp to download best audio quality ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'noplaylist': True, 'quiet': True, 'outtmpl': output_path[:-4] # Use the custom path as the output template } # Use yt-dlp to extract information and download the audio file with yt_dlp.YoutubeDL(ydl_opts) as ydl: info = ydl.extract_info(url, download=True) title = info.get('title') # Extract the title from video information # Load the downloaded file using eyed3 and add ID3 tags audiofile = eyed3.load(output_path) if audiofile.tag is None: # Create an ID3 tag if none exist audiofile.tag = eyed3.id3.Tag() audiofile.tag.file_info = eyed3.id3.FileInfo(output_path) print(f"Downloaded: {title}") audiofile.tag.title = title audiofile.tag.save() # Save the metadata # Use VLC to play the downloaded audio file player = vlc.MediaPlayer(output_path) player.play() # Wait for the audio to start playing and check periodically if it is still playing time.sleep(1) # Short initial delay to allow playback to start while player.is_playing(): time.sleep(1) # Check every second if it is still playing player.stop() # Stop playing after the audio is done if __name__ == "__main__": #youtube_url = "https://www.youtube.com/watch?v=szeXkBYq5HU" youtube_url = "https://www.youtube.com/watch?v=BYiraKCTViY&list=PLdQb1ybxFDih_SbfzdjGIlf3Tylztpc4Q" download_and_play(youtube_url)