一、環境準備
確保當前系統已安裝了wxPython 、 yt-dlp 和FFmpeg。當前主要支持下載youtube音視頻
1、安裝wxPython
pip install wxPython
2、安裝yt-dp
pip install wxPython yt-dlp
3、安裝FFmpeg
在Windows 10上通過命令行安裝FFmpeg,最簡便的方式是使用包管理器,比如Scoop或Chocolatey。以下是使用這兩種工具的步驟:
① 使用Scoop安裝FFmpeg
如果還沒有安裝Scoop,首先需要按照Scoop官網上的說明進行安裝。打開PowerShell并運行以下命令來安裝Scoop(如果尚未安裝):
Set-ExecutionPolicy RemoteSigned -scope CurrentUser
irm get.scoop.sh | iex
安裝完Scoop后,你可以通過以下命令安裝FFmpeg:
scoop install ffmpeg
② 使用Chocolatey安裝FFmpeg
如果更傾向于使用Chocolatey,首先確保已經安裝了Chocolatey。可以通過Chocolatey官網獲取安裝指南。
通常,可以在管理員模式下的PowerShell中運行以下命令來安裝Chocolatey:
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
安裝完Chocolatey后,可以通過以下命令安裝FFmpeg:
choco install ffmpeg
無論你選擇哪種方式安裝FFmpeg,完成后都可以通過命令行輸入以下命令來驗證是否安裝成功:
ffmpeg -version
如果你看到FFmpeg的版本信息以及其他相關細節,那么說明FFmpeg已經正確安裝,并且可以通過命令行使用了。
請注意,為了使這些命令在任何目錄下都能生效,可能需要重啟計算機或者重新打開一個新的命令提示符窗口。此外,確保你的環境變量Path包含了FFmpeg的安裝路徑,這樣系統才能識別ffmpeg命令。通過上述方法安裝時,通常會自動處理好這個問題。
二、代碼編寫
編寫名字為downloader.py的python代碼文件
import wx
import yt_dlp
import threadingclass DownloaderFrame(wx.Frame):def __init__(self):super().__init__(None, title="Downloader", size=(400, 350))self.panel = wx.Panel(self)self.source_label = wx.StaticText(self.panel, label="Audio or video URL:")self.source_text = wx.TextCtrl(self.panel)self.source_label.SetBackgroundColour(wx.Colour(173, 216, 230)) # 設置背景為淺藍色self.source_label.SetForegroundColour(wx.Colour(0, 0, 128)) # 設置文本顏色為黑色,確保對比度良好self.folder_label = wx.StaticText(self.panel, label="Save Folder:")self.folder_text = wx.TextCtrl(self.panel)self.folder_label.SetBackgroundColour(wx.Colour(173, 216, 230)) # 設置背景為淺藍色self.folder_label.SetForegroundColour(wx.Colour(0, 0, 128)) # 設置文本顏色為黑色,確保對比度良好self.folder_button = wx.Button(self.panel, label="Browse...")self.folder_button.Bind(wx.EVT_BUTTON, self.browse_folder)self.quality_label = wx.StaticText(self.panel, label="Quality:")self.quality_choice = wx.ComboBox(self.panel, choices=[], style=wx.CB_READONLY)self.quality_label.SetBackgroundColour(wx.Colour(173, 216, 230)) # 設置背景為淺藍色self.quality_label.SetForegroundColour(wx.Colour(0, 0, 128)) # 設置文本顏色為黑色,確保對比度良好self.start_button = wx.Button(self.panel, label="Start Download")self.start_button.Bind(wx.EVT_BUTTON, self.start)self.process_label = wx.StaticText(self.panel, label="Percentage:")self.process_bar = wx.Gauge(self.panel, range=100)self.process_label.SetBackgroundColour(wx.Colour(173, 216, 230)) # 設置背景為淺藍色self.process_label.SetForegroundColour(wx.Colour(0, 0, 128)) # 設置文本顏色為黑色,確保對比度良好self.sizer = wx.BoxSizer(wx.VERTICAL)self.sizer.Add(self.source_label, 0, wx.ALL, 5)self.sizer.Add(self.source_text, 0, wx.EXPAND | wx.ALL, 5)self.sizer.Add(self.folder_label, 0, wx.ALL, 5)self.sizer.Add(self.folder_text, 0, wx.EXPAND | wx.ALL, 5)self.sizer.Add(self.folder_button, 0, wx.ALL, 5)self.sizer.Add(self.quality_label, 0, wx.ALL, 5)self.sizer.Add(self.quality_choice, 0, wx.EXPAND | wx.ALL, 5)self.sizer.Add(self.start_button, 0, wx.ALL, 5)self.sizer.Add(self.process_label, 0, wx.ALL, 5)self.sizer.Add(self.process_bar, 0, wx.EXPAND | wx.ALL, 5)self.panel.SetSizer(self.sizer)self.Show()def browse_folder(self, event):dlg = wx.DirDialog(self, "Choose a directory", style=wx.DD_DEFAULT_STYLE)if dlg.ShowModal() == wx.ID_OK:self.folder_text.SetValue(dlg.GetPath())dlg.Destroy()def get_video_formats(self, url):with yt_dlp.YoutubeDL({}) as ydl:info_dict = ydl.extract_info(url, download=False)#print(info_dict) # 添加此行來查看所有可用格式formats = info_dict.get('formats', [])#print("Available formats:", formats) # 打印所有可用格式以供調試self.quality_choice.Clear()best_format_id = None # 初始化為Nonehas_1080p = False# 首先嘗試找到1080p或更高的視頻格式for f in formats:if 'height' in f and 'format_id' in f and f['vcodec'] != 'none' and f['acodec'] != 'none':display_str = f"{f['format_id']} - {f['height']}p"if f['height'] >= 1080: # 檢查是否為1080p或更高if not has_1080p or f['height'] > int(best_format_id.split(" - ")[1][:-1]):best_format_id = display_strhas_1080p = True# 如果沒有找到1080p或更高的格式,則選擇其他可用的最高分辨率if not has_1080p:for f in formats:if 'height' in f and 'format_id' in f and f['vcodec'] != 'none' and f['acodec'] != 'none':display_str = f"{f['format_id']} - {f['height']}p"if best_format_id is None or ('height' in f and f['height'] > int(best_format_id.split(" - ")[1][:-1])):best_format_id = display_str# 添加所有滿足條件的格式到下拉列表中供用戶選擇for f in formats:if 'height' in f and 'format_id' in f and f['vcodec'] != 'none' and f['acodec'] != 'none':self.quality_choice.Append(f"{f['format_id']} - {f['height']}p")if self.quality_choice.GetCount() > 0:self.quality_choice.SetSelection(0)return best_format_iddef start(self, event):url = self.source_text.GetValue()save_folder = self.folder_text.GetValue()# 獲取并填充清晰度選項best_format = self.get_video_formats(url)#print(best_format)if not best_format: # 如果沒有找到任何格式wx.MessageBox("No suitable video format found.", "Error", wx.OK | wx.ICON_ERROR)returndownload_thread = threading.Thread(target=self.download_Audio_or_video, args=(url, save_folder, best_format))download_thread.start()def download_Audio_or_video(self, url, save_folder, best_format):selected_format = self.quality_choice.GetStringSelection()format_id = selected_format.split(" - ")[0] if selected_format else best_format.split(" - ")[0] # 提取format idoptions = {'outtmpl': f'{save_folder}/%(title)s.%(ext)s',#'format': 'best', # 使用最佳質量'format': format_id,'progress_hooks': [self.update_progress],}try:with yt_dlp.YoutubeDL(options) as ydl:ydl.download([url])wx.CallAfter(wx.MessageBox, 'Download completed!', 'Info', wx.OK | wx.ICON_INFORMATION)except Exception as e:wx.CallAfter(wx.MessageBox, f'Download error occurred: {str(e)}', 'Error', wx.OK | wx.ICON_ERROR)def update_progress(self, progress ):if 'total_bytes' in progress and 'downloaded_bytes' in progress:percentage = int(progress['downloaded_bytes'] * 100 / progress['total_bytes'])wx.CallAfter(self.process_bar.SetValue, percentage)app = wx.App(False)
frame = DownloaderFrame()
app.MainLoop()
三、代碼運行測試
1.命令行運行測試
1.python downloader.py
三、其他方式
或者直接利用exe下載工具來進行命令行下載
參考文件:
https://blog.csdn.net/qq_31339083/article/details/132195733
https://blog.csdn.net/winniezhang/article/details/132127382