import random import tempfile from pytube import Playlist, YouTube from pydub import AudioSegment class YouTubeAudioExtractor: def __init__(self, playlist_url): self.playlist_url = playlist_url self.video_url = None self.audio_file = None def select_random_video(self): """Select a random video from the playlist.""" playlist = Playlist(self.playlist_url) videos = list(playlist.video_urls) self.video_url = random.choice(videos) return self.video_url def extract_audio(self): """Extract audio from the selected video and save it as an MP3 file.""" if not self.video_url: raise ValueError("No video selected. Please select a video first.") video = YouTube(self.video_url) audio_stream = video.streams.filter(only_audio=True).first() with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_audio_file: audio_stream.download(output_path=temp_audio_file.name) temp_audio_file.close() audio = AudioSegment.from_file(temp_audio_file.name) with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as mp3_file: audio.export(mp3_file.name, format="mp3") self.audio_file = mp3_file.name return self.audio_file class YouTubeAudioPlayer: def __init__(self, audio_file): self.audio_file = audio_file def play_audio(self): """Play the extracted audio.""" # This method can be expanded to include playback logic. # Currently, it only provides the path to the audio file. return self.audio_file