研究PySide与youtube_dl结合实现视频下载,抽丝剥蚕,步步维艰,却也颇有意思。
记录初始心得。界面以PySide之Qt编写,调用youtube_dl下载,回调出下载进度,代码如下:
# encoding: utf-8 from __future__ import unicode_literals from PySide.QtGui import * from PySide.QtCore import * from main_ui import * import youtube_dl import threading class MainWindow(QMainWindow, Ui_Main): update_info = Signal(dict) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.btnGet.setEnabled(False) self.txtUrl.setText('https://www.youtube.com/watch?v=dvSLaHj9VVM') self.update_info.connect(self.safe_hook_progress) def hook_progress(self, d): self.update_info.emit(d) def safe_hook_progress(self, d): info = '' if d['status'] == 'downloading': info = 'downloaded_bytes: ' + str(d['downloaded_bytes']) + ', elapsed: ' + str( d['elapsed']) + ', speed: ' + str(d['speed']) + ', filename: ' + d['filename']; elif d['status'] == 'finished': info = '\r\ncomplete!' self.txtUrl.setEnabled(True) self.btnGet.setEnabled(True) if info != '': self.txtInfo.append(info) # self.txtInfo.setText(info) def get_opts(self): ydl_opts = { 'format': 'bestvideo', # 'outtmpl': os.path.join(app.config['VIDEOS_FOLDER'], '%(id)s.%(ext)s'), # 'logger': MyLogger(), 'progress_hooks': [self.hook_progress], } return ydl_opts def download(self, url): print 'download......', url if url.strip() == '': return ydl = youtube_dl.YoutubeDL(self.get_opts()) ydl.download([url]) @Slot() def on_txtUrl_returnPressed(self): if self.btnGet.isEnabled(): self.btnGet.click() @Slot(str) def on_txtUrl_textChanged(self, s): self.btnGet.setEnabled(s != '') @Slot() def on_btnGet_clicked(self): self.txtUrl.setEnabled(False) self.btnGet.setEnabled(False) self.txtInfo.setText('') t = threading.Thread(target=MainWindow.download, args=(self, self.txtUrl.text()), name='thread') t.start()
效果如图所示:
参考: