Update: Refactored the code
This commit is contained in:
@@ -0,0 +1,41 @@
|
||||
import os
|
||||
|
||||
from pydub import AudioSegment
|
||||
from pytube import YouTube
|
||||
|
||||
|
||||
class FileManager:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def download_youtube_audio(self, youtube_link, filename):
|
||||
yt = YouTube(youtube_link)
|
||||
|
||||
# Get the highest quality audio stream
|
||||
audio_stream = yt.streams.get_audio_only()
|
||||
|
||||
# Download if the file doesn't already exist
|
||||
if not os.path.exists(filename):
|
||||
audio_stream.download(filename=filename)
|
||||
|
||||
def convert_to_wav(self, mp4_file, wav_file):
|
||||
sound = AudioSegment.from_file(mp4_file, format="mp4")
|
||||
sound.export(wav_file, format="wav")
|
||||
|
||||
def load_local_file(self, local_file_path):
|
||||
# Check the file type
|
||||
ext = os.path.splitext(local_file_path)[-1].lower()
|
||||
|
||||
if ext == ".mp4":
|
||||
wav_file = local_file_path.replace(".mp4", ".wav")
|
||||
self.convert_to_wav(local_file_path, wav_file)
|
||||
return wav_file
|
||||
elif ext == ".mp3":
|
||||
wav_file = local_file_path.replace(".mp3", ".wav")
|
||||
audio = AudioSegment.from_file(local_file_path, format="mp3")
|
||||
audio.export(wav_file, format="wav")
|
||||
return wav_file
|
||||
elif ext == ".wav":
|
||||
return local_file_path
|
||||
else:
|
||||
raise ValueError("Unsupported file format.")
|
||||
Reference in New Issue
Block a user