-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.py
86 lines (66 loc) · 2.95 KB
/
MainWindow.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import os
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from pytube import Playlist,YouTube
import ffmpeg
from pathvalidate import sanitize_filename # http://pypi.org/project/pathvalidate/
from Ui_MainWindow import Ui_MainWindow
class MainWindow(QtWidgets.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# ui init
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# MainWindow Title
self.setWindowTitle('Youtube2Mp3')
# set window icon
icon_path = self.resource_path('icon/icon_window.png')
self.setWindowIcon(QtGui.QIcon(icon_path))
# save place
self.save_dir = '轉換的音樂'
os.makedirs(self.save_dir, exist_ok=True)
# convert button
self.ui.convertButton.clicked.connect(self.convert)
# status label
self.ui.statusLabel.setText('')
# mp4 filepath
self.mp4_file_path = ''
# for packaging one file on pyinstaller
def resource_path(self, relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath('.')
return os.path.join(base_path, relative_path)
def convert(self):
url_text = self.ui.urlEdit.text() # https://www.youtube.com/watch?v=biSB9_Z3VUw
if url_text is not '':
QtWidgets.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
try:
video = YouTube(url_text)
video_name = sanitize_filename(video.title)
if video_name=='Youtube':
raise NotImplementedError
self.mp4_file_path = os.path.join(self.save_dir, f'{video_name}.mp4')
video.streams.filter(progressive=True, file_extension='mp4').first().download(output_path=self.save_dir, filename=video_name)
mp3_file_path = os.path.join(self.save_dir, f'{video_name}.mp3')
stream = ffmpeg.input(self.mp4_file_path)
stream = ffmpeg.output(stream, mp3_file_path)
ffmpeg.run(stream, overwrite_output=True)
except Exception as e: # fail to convert
print(e)
self.ui.statusLabel.setText('轉換失敗,請重試一次')#self.ui.statusLabel.setText('轉換失敗,請重試一次')
else:
self.ui.statusLabel.setText('轉換成功')
if os.path.exists(self.mp4_file_path): os.remove(self.mp4_file_path)
QtWidgets.QApplication.restoreOverrideCursor()
self.ui.urlEdit.setText('')
else:
self.ui.statusLabel.setText('請輸入 Youtube 網址')
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())