├── yt-dlp.py └── README.md /yt-dlp.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | import os 3 | import re 4 | import glob 5 | 6 | def extract_video_url(playlist_url): 7 | """Extracts the single video URL from a playlist URL.""" 8 | match = re.search(r"v=([a-zA-Z0-9_-]+)", playlist_url) 9 | if match: 10 | return f"https://www.youtube.com/watch?v={match.group(1)}" 11 | return playlist_url 12 | 13 | def convert_video(input_file, target_format): 14 | """Converts the video to the specified format using H.264 for video and AAC for audio.""" 15 | # Use the base name of the downloaded file for the converted output 16 | base_name = os.path.splitext(os.path.basename(input_file))[0] 17 | output_file = os.path.join(os.path.dirname(input_file), f"{base_name}.{target_format}") 18 | 19 | if target_format == "mp4": 20 | command = [ 21 | "ffmpeg", "-i", input_file, 22 | "-vcodec", "libx264", "-acodec", "aac", 23 | "-b:v", "1000k", "-b:a", "128k", 24 | "-preset", "fast", "-crf", "23", "-movflags", "+faststart", 25 | output_file 26 | ] 27 | elif target_format == "mkv": 28 | command = [ 29 | "ffmpeg", "-i", input_file, 30 | "-c:v", "libx264", "-c:a", "aac", 31 | "-b:v", "1000k", "-b:a", "128k", 32 | output_file 33 | ] 34 | else: 35 | print("❌ Unsupported format. No conversion performed.") 36 | return None 37 | 38 | subprocess.run(command) 39 | return output_file 40 | 41 | def download_media(video_url, file_type, quality, is_playlist): 42 | """Downloads media (MP3 or MP4) based on user choices and offers conversion afterward.""" 43 | output_dir = "output" 44 | os.makedirs(output_dir, exist_ok=True) 45 | 46 | audio_quality_map = {"low": "50K", "medium": "128K", "high": "192K"} 47 | video_quality_map = {"low": "360", "medium": "720", "high": "1080"} 48 | 49 | # Filename template uses YouTube video title and extension 50 | filename = os.path.join(output_dir, "%(title)s.%(ext)s") 51 | command = ["yt-dlp", "-o", filename] 52 | 53 | if file_type == "mp3": 54 | bitrate = audio_quality_map.get(quality, "128K") 55 | command += ["-x", "--audio-format", "mp3", "--audio-quality", bitrate] 56 | elif file_type == "mp4": 57 | resolution = video_quality_map.get(quality, "720") 58 | command += [ 59 | "-f", f"bv*[height<={resolution}]+ba/best", 60 | "--merge-output-format", "mp4" 61 | ] 62 | 63 | if not is_playlist: 64 | command.append("--no-playlist") 65 | 66 | # Use yt-dlp's --print after_move:filepath to capture the output filename 67 | command += ["--print", "after_move:filepath"] 68 | command.append(video_url) 69 | result = subprocess.run(command, capture_output=True, text=True) 70 | 71 | # Conversion step for video files 72 | if file_type == "mp4": 73 | # Get the actual output filename from yt-dlp's output 74 | output_lines = result.stdout.strip().splitlines() 75 | mp4_files = [line for line in output_lines if line.lower().endswith(".mp4")] 76 | if mp4_files: 77 | input_file = mp4_files[-1] # Use the last .mp4 file printed 78 | convert_choice = input("Do you want to convert the file to another format? (yes/no): ").strip().lower() 79 | if convert_choice == "yes": 80 | target_format = input("Enter target format (mp4/mkv): ").strip().lower() 81 | output_file = convert_video(input_file, target_format) 82 | if output_file: 83 | print(f"✅ Converted video saved as: {output_file}") 84 | else: 85 | print("❌ No MP4 file found. Conversion skipped.") 86 | # If file type is mp3, no further conversion is applied. 87 | 88 | if __name__ == "__main__": 89 | url = input("Enter YouTube URL: ").strip() 90 | 91 | # Check if the URL contains a playlist 92 | is_playlist = "list=" in url 93 | if is_playlist: 94 | choice = input("This is a playlist. Do you want to download the entire playlist? (yes/no): ").strip().lower() 95 | if choice != "yes": 96 | url = extract_video_url(url) 97 | is_playlist = False 98 | 99 | file_type = input("Enter file type (mp3/mp4): ").strip().lower() 100 | if file_type not in ["mp3", "mp4"]: 101 | print("Invalid file type! Defaulting to mp4.") 102 | file_type = "mp4" 103 | 104 | print("Choose quality: low, medium, high") 105 | quality = input("Enter quality (default: medium): ").strip().lower() or "medium" 106 | 107 | download_media(url, file_type, quality, is_playlist) 108 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # YouTube Media Downloader 2 | 3 | ## Overview 4 | 5 | This script allows users to download and convert YouTube videos and playlists into MP3 or MP4 formats. It utilizes `yt-dlp` for downloading and `ffmpeg` for conversion, ensuring high-quality media processing. 6 | 7 | ## Features 8 | 9 | - Download YouTube videos or entire playlists 10 | - Convert downloaded videos to MP4 or MKV format 11 | - Supports multiple quality options for both audio and video 12 | - Uses `yt-dlp` for reliable downloads 13 | - Uses `ffmpeg` for high-quality media conversion 14 | 15 | ## Prerequisites 16 | 17 | Ensure you have the following installed on your system: 18 | 19 | - **Python** (latest version recommended) 20 | - **yt-dlp** (`pip install yt-dlp`) 21 | - **ffmpeg** (install via package manager or download from [ffmpeg.org](https://ffmpeg.org)) 22 | 23 | ### Installing Prerequisites 24 | 25 | **For Python:** 26 | 27 | ```sh 28 | # Windows (using official installer) 29 | # Download Python from: https://www.python.org/downloads/ 30 | # Run the installer and follow the setup instructions 31 | 32 | # Windows (using winget) 33 | winget install Python.Python.3 34 | 35 | # macOS (using Homebrew) 36 | brew install python 37 | 38 | # Linux (Ubuntu/Debian) 39 | sudo apt install python3 40 | 41 | # Linux (Fedora) 42 | sudo dnf install python3 43 | ``` 44 | 45 | **For yt-dlp:** 46 | 47 | ```sh 48 | pip install yt-dlp 49 | ``` 50 | 51 | **For ffmpeg:** 52 | 53 | - **Windows:** 54 | 1. Download the latest build from [gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z](https://www.gyan.dev/ffmpeg/builds/ffmpeg-git-full.7z). 55 | 2. Extract the archive to a folder, e.g., `C:\ffmpeg`. 56 | 3. Open the extracted folder and go to the `bin` directory. 57 | 4. You will find `ffmpeg.exe`, `ffplay.exe`, and `ffprobe.exe` inside `bin`. 58 | 5. Add the full path to the `bin` folder (e.g., `C:\ffmpeg\bin`) to your system PATH environment variable: 59 | - Open the Start menu and search for **Environment Variables**. 60 | - Click **Edit the system environment variables**. 61 | - In the System Properties window, click **Environment Variables...** 62 | - Under **System variables**, find and select the **Path** variable, then click **Edit**. 63 | - Click **New** and add the path to your ffmpeg `bin` folder (e.g., `C:\ffmpeg\bin`). 64 | - Click **OK** to save and close all windows. 65 | 6. Open a new Command Prompt and run `ffmpeg -version` to verify the installation. 66 | - **macOS:** `brew install ffmpeg` 67 | - **Linux (Ubuntu/Debian):** `sudo apt install ffmpeg` 68 | - **Linux (Fedora):** `sudo dnf install ffmpeg` 69 | 70 | To verify installation, open a terminal/command prompt and type: 71 | 72 | ```sh 73 | python --version 74 | yt-dlp --version 75 | ffmpeg -version 76 | ``` 77 | 78 | ## Installation 79 | 80 | 1. Clone or download the script. 81 | 2. Ensure `python`, `yt-dlp` and `ffmpeg` are installed and accessible from the command line. 82 | 83 | > **Windows users:** For a step-by-step installation guide (including Python setup and environment variables), see the **Windows Installation Guide** section in [Detailed Installation Guide](https://github.com/abdelrahman-ahmed-nassar/YouTube-Media-Downloader-using-yt-dlp/wiki/Detailed-Installation-Guide). 84 | 85 | ## Usage 86 | 87 | Run the script in a terminal: 88 | 89 | ```sh 90 | python yt-dlp.py 91 | ``` 92 | 93 | ### Navigating to the Script Directory 94 | 95 | 1. Open a terminal or command prompt 96 | 2. Navigate to the directory containing the script: 97 | ```sh 98 | cd path/to/script/directory 99 | ``` 100 | - **Windows example:** `cd C:\Users\YourName\Downloads\YOUTUBE-MEDIA-DOWNLOADER-USING-YT-DLP` 101 | - **macOS/Linux example:** `cd ~/Downloads/YOUTUBE-MEDIA-DOWNLOADER-USING-YT-DLP` 102 | 3. Run the script with: 103 | ```sh 104 | python yt-dlp.py 105 | ``` 106 | 107 | Follow the prompts: 108 | 109 | 1. Enter the YouTube video or playlist URL. 110 | 2. Choose whether to download an entire playlist or a single video. 111 | 3. Select the file type (`mp3` or `mp4`). 112 | 4. Select the quality level (`low`, `medium`, or `high`). 113 | 5. If downloading an MP4 file, you may choose to convert it to another format. 114 | 115 | ### Example Usage 116 | 117 | **Download a single video in MP4 format with high quality:** 118 | 119 | ``` 120 | Enter YouTube URL: https://www.youtube.com/watch?v=example 121 | Enter file type (mp3/mp4): mp4 122 | Enter quality (default: medium): high 123 | ``` 124 | 125 | **Download an MP3 file with medium quality:** 126 | 127 | ``` 128 | Enter YouTube URL: https://www.youtube.com/watch?v=example 129 | Enter file type (mp3/mp4): mp3 130 | Enter quality (default: medium): medium 131 | ``` 132 | 133 | ## Output 134 | 135 | - All downloaded media will be stored in the `output/` directory. 136 | - Converted video files will be stored in the same directory with the chosen format. 137 | 138 | ## Notes 139 | 140 | - If a playlist URL is provided, the script will prompt you to download the full playlist or just a single video. 141 | - MP4 files are downloaded in the best available format up to the selected resolution. 142 | - MP3 files are extracted with the specified bitrate. 143 | - Conversion only applies to MP4 files and supports MP4 and MKV formats. 144 | 145 | ## License 146 | 147 | This script is open-source and available for use and modification under the MIT License. 148 | 149 | ## Detailed Version 150 | 151 | For advanced configuration options, troubleshooting tips, and developer documentation, please refer to the [Detailed Installation Guide](https://github.com/abdelrahman-ahmed-nassar/YouTube-Media-Downloader-using-yt-dlp/wiki/Detailed-Installation-Guide) file included with this project. 152 | 153 | --------------------------------------------------------------------------------