python压缩视频文件_python 批量压缩手机视频

该博客介绍了一个Python脚本,用于批量压缩手机视频。脚本通过ffmpeg库检测视频的分辨率和比特率,根据预设条件决定是否进行压缩。压缩过程中,脚本会创建一个名为'compress_output'的目录来存放压缩后的视频。如果视频比特率过小或文件大小超过150KB,将使用ffmpeg进行压缩。用户可以通过命令行参数输入要压缩的文件或目录路径。
摘要由CSDN通过智能技术生成

importsysimportosfrom concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor #线程池,进程池#import zlib

importthreading#import platform#from PIL import Image

importffmpegfrom shutil importcopyfiledefget_file_dir(file):"""获取文件目录通用函数"""fullpath=os.path.abspath(os.path.realpath(file))returnos.path.dirname(fullpath)defSaveVideo(input_file):

file_name=os.path.basename(input_file)

arr= file_name.split('.')

new_file_name= arr[0] + '_compress.' + arr[1]

output_path= os.path.join(get_file_dir(input_file), 'compress_output')

output_file=os.path.join(output_path, new_file_name)if notos.path.isdir(output_path):

os.makedirs(output_path)if(os.path.exists(output_file)):print("已存在,跳过压缩")return

#执行probe执行

probe =ffmpeg.probe(input_file)

video_stream= next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)if video_stream isNone:print('No video stream found', file=sys.stderr)return

#sys.exit(1)

#宽度

width = int(video_stream['width'])## 高度

height = int(video_stream['height'])## 帧数

#num_frames = int(video_stream['nb_frames'])

## 时长

#time = (video_stream['duration'])

#比特率

bitrate = (video_stream['bit_rate'])#print('width: {}'.format(width))

#print('height: {}'.format(height))

#print('num_frames: {}'.format(num_frames))

#print('time: {}'.format(time))

#print('bitrate: {}'.format(bitrate))

if ((width == 720 and height == 1280) or (width == 1280 and height == 720)):if (int(bitrate) < 2500 * 1024):print("比特率过小,跳过压缩")try:

copyfile(input_file, output_file)exceptIOError as e:print("Unable to copy file. %s" %e)return

elif ((width == 1080 and height == 1920) or (width == 1920 and height == 1080)):if (int(bitrate) < 5000 * 1024):print("比特率过小,跳过压缩")try:

copyfile(input_file, output_file)exceptIOError as e:print("Unable to copy file. %s" %e)return

else:if (int(bitrate) < 2000 * 1024):print("比特率过小,跳过压缩")try:

copyfile(input_file, output_file)exceptIOError as e:print("Unable to copy file. %s" %e)returnfpsize= os.path.getsize(input_file) / 1024

if fpsize >= 150.0: #大于150KB的视频需要压缩

compress = "ffmpeg -i {} -r 25 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -crf 26 -profile:v baseline -acodec aac -b:a 96k -strict -2 {}".format(input_file, output_file)

isRun=os.system(compress)#if outName:

#compress = "ffmpeg -i {} -r 25 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -crf 24 -profile:v baseline -acodec aac -b:a 128k -strict -2 {}".format(

#fileInputPath, fileOutPath)

#isRun = os.system(compress)

#else:

#compress = "ffmpeg -i {} -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline -crf 23 -acodec aac -b:a 32k -strict -5 {}".format(self.fileInputPath, self.fileInputPath)

#isRun = os.system(compress)

if isRun !=0:return (isRun, "没有安装ffmpeg")returnTrueelse:returnTruedefCompress_Video(self):#异步保存打开下面的代码,注释同步保存的代码

thr = threading.Thread(target=self.SaveVideo)

thr.start()defcheck_path(input_path):"""如果输入的是文件则直接压缩,如果是文件夹则先遍历"""

ifos.path.isfile(input_path):

SaveVideo(input_path)elifos.path.isdir(input_path):

dirlist=os.walk(input_path)for root, dirs, files indirlist:if (not (root.endswith("\\compress_output") or root.endswith("/compress_output"))):

i=0for filename infiles:

i= i + 1SaveVideo(os.path.join(root, filename))#process_pool.submit(SaveVideo, os.path.join(root, filename))

#compress_by_tinypng(os.path.join(root, filename))

else:print(u'目标文件(夹)不存在,请确认后重试。')if __name__ == "__main__":

process_pool= ProcessPoolExecutor(1) #定义5个进程

b = sys.argv[1:] #测试压缩

len_param =len(sys.argv)if len_param != 2:print('请使用: %s [inputpath] [outputpath]' %os.path.basename(sys.argv[0]))else:

check_path(b[0])

input("Press 请耐心等待\n")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值