Spaces:
Sleeping
Sleeping
Update thaTube.py
Browse files- thaTube.py +45 -0
thaTube.py
CHANGED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import tempfile
|
| 3 |
+
from pytube import Playlist, YouTube
|
| 4 |
+
from pydub import AudioSegment
|
| 5 |
+
|
| 6 |
+
class YouTubeAudioExtractor:
|
| 7 |
+
def __init__(self, playlist_url):
|
| 8 |
+
self.playlist_url = playlist_url
|
| 9 |
+
self.video_url = None
|
| 10 |
+
self.audio_file = None
|
| 11 |
+
|
| 12 |
+
def select_random_video(self):
|
| 13 |
+
"""Select a random video from the playlist."""
|
| 14 |
+
playlist = Playlist(self.playlist_url)
|
| 15 |
+
videos = list(playlist.video_urls)
|
| 16 |
+
self.video_url = random.choice(videos)
|
| 17 |
+
return self.video_url
|
| 18 |
+
|
| 19 |
+
def extract_audio(self):
|
| 20 |
+
"""Extract audio from the selected video and save it as an MP3 file."""
|
| 21 |
+
if not self.video_url:
|
| 22 |
+
raise ValueError("No video selected. Please select a video first.")
|
| 23 |
+
|
| 24 |
+
video = YouTube(self.video_url)
|
| 25 |
+
audio_stream = video.streams.filter(only_audio=True).first()
|
| 26 |
+
|
| 27 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp4') as temp_audio_file:
|
| 28 |
+
audio_stream.download(output_path=temp_audio_file.name)
|
| 29 |
+
temp_audio_file.close()
|
| 30 |
+
|
| 31 |
+
audio = AudioSegment.from_file(temp_audio_file.name)
|
| 32 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix='.mp3') as mp3_file:
|
| 33 |
+
audio.export(mp3_file.name, format="mp3")
|
| 34 |
+
self.audio_file = mp3_file.name
|
| 35 |
+
return self.audio_file
|
| 36 |
+
|
| 37 |
+
class YouTubeAudioPlayer:
|
| 38 |
+
def __init__(self, audio_file):
|
| 39 |
+
self.audio_file = audio_file
|
| 40 |
+
|
| 41 |
+
def play_audio(self):
|
| 42 |
+
"""Play the extracted audio."""
|
| 43 |
+
# This method can be expanded to include playback logic.
|
| 44 |
+
# Currently, it only provides the path to the audio file.
|
| 45 |
+
return self.audio_file
|