diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..cf45c29 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.venv/ +*.mp3 +*.ico \ No newline at end of file diff --git a/YP3.exe b/YP3.exe new file mode 100644 index 0000000..acae532 Binary files /dev/null and b/YP3.exe differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..d4c9fde --- /dev/null +++ b/main.py @@ -0,0 +1,81 @@ +import yt_dlp +import os +import subprocess +import sys +from tqdm import tqdm + +# ANSI 顏色代碼 +GREEN = '\033[92m' +RED = '\033[91m' +RESET = '\033[0m' + +def check_ffmpeg(): + try: + subprocess.run(["ffmpeg", "-version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + return True + except FileNotFoundError: + return False + +def install_ffmpeg_instructions(): + print("請先安裝 ffmpeg 才能繼續操作。") + print("安裝說明:") + if sys.platform.startswith('win'): + print("Windows: 使用 Chocolatey 安裝,執行命令:choco install ffmpeg") + elif sys.platform.startswith('darwin'): + print("macOS: 使用 Homebrew 安裝,執行命令:brew install ffmpeg") + elif sys.platform.startswith('linux'): + print("Linux: 使用包管理器安裝,例如 Ubuntu 執行命令:sudo apt-get install ffmpeg") + print("安裝完成後,請重新運行此程式。") + +def progress_hook(d): + if d['status'] == 'downloading': + pbar.update(d['downloaded_bytes'] - pbar.n) + elif d['status'] == 'finished': + pbar.close() + print("下載完成,正在轉換為 MP3...") + +def download_youtube_audio(url): + try: + ydl_opts = { + 'format': 'bestaudio/best', + 'postprocessors': [{ + 'key': 'FFmpegExtractAudio', + 'preferredcodec': 'mp3', + 'preferredquality': '192', + }], + 'outtmpl': '%(title)s.%(ext)s', + 'progress_hooks': [progress_hook], + 'quiet': True, + 'no_warnings': True, + } + + with yt_dlp.YoutubeDL(ydl_opts) as ydl: + info = ydl.extract_info(url, download=False) + filename = ydl.prepare_filename(info) + global pbar + pbar = tqdm(total=info.get('filesize', 0), unit='B', unit_scale=True, desc=f"下載進度 - {info['title']}") + + ydl.download([url]) + + base, ext = os.path.splitext(filename) + new_file = base + '.mp3' + + print(f"成功下載並轉換為MP3: {GREEN}{new_file}{RESET}") + except yt_dlp.utils.DownloadError as e: + print(f"{RED}下載錯誤{RESET}") + except Exception as e: + print(f"{RED}發生未知錯誤{RESET}") + finally: + if 'pbar' in globals(): + pbar.close() + +# 主程序 +if __name__ == "__main__": + if not check_ffmpeg(): + install_ffmpeg_instructions() + else: + youtube_urls = input("請輸入YouTube影片網址(多個網址請用空格分隔): ").split() + for url in youtube_urls: + print(f"\n正在處理: {url}") + download_youtube_audio(url) +input() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b79964f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,13 @@ +Brotli==1.1.0 +certifi==2024.8.30 +charset-normalizer==3.3.2 +colorama==0.4.6 +idna==3.10 +mutagen==1.47.0 +pycryptodomex==3.20.0 +pytube==15.0.0 +requests==2.32.3 +tqdm==4.66.5 +urllib3==2.2.3 +websockets==13.1 +yt-dlp==2024.9.27