File size: 1,678 Bytes
879d534
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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