前置条件:
1.安装PyQT5
pip install PyQt5
pip install PyQt5 -i https://pypi.douban.com/simple #通过豆瓣镜像源安装PyQT5
2.下载FFmpeg
官网地址 Download FFmpeg
本程序只用到了ffmpeg这个可执行程序(probe是用于编码,play是用于播放),ffmpeg.exe必须放置在最终程序的同一路径下或者配置到环境变量中
3.安装Pyinstaller
为了最终打包代码为一个可执行程序,下载方式如下
pip install pyinstaller #也可以像第一步用镜像源下载
代码(可直接运行):
1.Python代码
import os
import sys
from datetime import datetime
from PyQt5.QtCore import Qt
from PyQt5.QtNetwork import QLocalServer, QLocalSocket
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QLabel, QSlider, QPushButton
from PyQt5.QtGui import QIcon
class VideoCompressor(QWidget):
def __init__(self):
super().__init__()
self.input_file = None
self.output_file = None
self.crf_value = 30
self.init_ui()
def init_ui(self):
layout = QVBoxLayout()
self.label = QLabel("拖动视频文件到窗口释放即可!")
layout.addWidget(self.label)
self.slider = QSlider(Qt.Horizontal)
self.slider.setMinimum(1) # 设置为1
self.slider.setMaximum(50) # 设置为50
self.slider.setValue(int(self.crf_value)) # 映射为整数
self.slider.valueChanged.connect(self.slider_changed)
layout.addWidget(self.slider)
self.crf_label = QLabel(f" CRF参数: {int(self.crf_value)}\n\n*CRF参数范围1至50,参数越大压缩效果越强\n 建议25-35之间") # 只显示整数部分
layout.addWidget(self.crf_label)
self.compress_button = QPushButton("开始压缩")
self.compress_button.resize(400,300)
self.compress_button.clicked.connect(self.compress_video)
layout.addWidget(self.compress_button)
self.setLayout(layout)
self.setGeometry(300, 300, 400, 200)
self.setWindowTitle('PW_Compress')
self.setAcceptDrops(True)
def slider_changed(self):
self.crf_value = int(self.slider.value())
self.crf_label.setText(f" CRF参数: {self.crf_value}\n\n*CRF参数范围1至50,参数越大压缩效果越强\n 建议25-35之间") # 只显示整数部分
def compress_video(self):
output_directory = os.path.dirname(self.input_file)
output_filename = self.get_output_filename()
self.output_file = output_directory + '/' + output_filename
compress_cmd = 'ffmpeg -i \"{inputfile}\" -crf {index} \"{outputfile}\"'.format(inputfile=self.input_file,
index=self.crf_value,
outputfile=self.output_file)
os.system(compress_cmd)
self.label.setText(f"压缩完成,输出文件:{self.output_file}")
def get_output_filename(self):
base_filename, extension = os.path.splitext(os.path.basename(self.input_file))
timestamp = datetime.now().strftime("%Y%m%d_%H%M")
output_filename = f"{base_filename}_[{timestamp}compressed]{extension}"
return output_filename
def dragEnterEvent(self, event):
mime_data = event.mimeData()
if mime_data.hasUrls() and len(mime_data.urls()) == 1:
file_path = mime_data.urls()[0].toLocalFile()
if os.path.isfile(file_path) and any(
file_path.lower().endswith(ext) for ext in ['.mp4', '.avi', '.mkv', '.mov']):
event.acceptProposedAction()
def dropEvent(self, event):
file_path = event.mimeData().urls()[0].toLocalFile()
if os.path.isfile(file_path) and any(
file_path.lower().endswith(ext) for ext in ['.mp4', '.avi', '.mkv', '.mov']):
self.input_file = file_path
self.label.setText(f"已选择文件:{self.input_file}")
if __name__ == '__main__':
try:
app = QApplication(sys.argv)
serverName = 'PW_Compress'
socket = QLocalSocket()
socket.connectToServer(serverName)
if socket.waitForConnected(500):
app.quit()
else:
localServer = QLocalServer()
localServer.listen(serverName)
compressor = VideoCompressor()
compressor.setWindowIcon(QIcon('Logo.ico'))
compressor.show()
sys.exit(app.exec_())
except:
print("启动异常")
代码结构:
2.使用Pyinstaller打包程序
在Terminal输入
pyinstaller -F -w 文件名.py
完成后会在路径下生成一个dist目录,可执行程序就在这个文件夹中
最终结果:
图标(我自己加了自己的icon,所以与默认图标不一致,如果想个性化定义,需要将想要的图片转为".ico"格式文件,Pyinstaller加 "-i 文件.ico"参数):
GUI界面:
操作步骤:
1.将想要压缩的视频拖入窗口,会自动识别文件绝对路径
2.调整CRF参数,数值越大压缩效果越强,但对画质损失也会越大。反之则效果弱,损失也小
3.点击压缩视频,开始压缩
4.需要压缩新的文件则拖新的文件进入,重复123步骤即可