Skip to content
Snippets Groups Projects
ytdownloader.py 1.05 KiB
import shutil
from pathlib import Path

import yt_dlp.postprocessor
from yt_dlp import YoutubeDL

class YTDownloader:
    def __init__(self, audiodir, videodir):
        self.audiodir = audiodir
        self.videodir = videodir

    def download(self, url: str, artist: str, song: str, spotify_uri: str):
        ydl_opts = {
            'format': 'mp4/best',
            'outtmpl': f'{str((Path(self.audiodir) / f"{artist} - {song} - {spotify_uri}").resolve())}.%(ext)s',
            # ℹ️ See help(yt_dlp.postprocessor) for a list of available Postprocessors and their arguments
            'keepvideo': True,
            'postprocessors': [{  # Extract audio using ffmpeg
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
            }]
        }
        with YoutubeDL(ydl_opts) as ydl:
            ydl.download(url)

        Path(self.videodir).mkdir(parents=True, exist_ok=True)
        shutil.move(Path(self.audiodir) / f"{artist} - {song} - {spotify_uri}.mp4", Path(self.videodir) / f"{artist} - {song} - {spotify_uri}.mp4")