python压缩视频

作者: zengde 分类: 笔记 发布时间: 2021-03-26 10:58
# ffmpeg -i 1.mp4 -r 10 -pix_fmt yuv420p -vcodec libx264 -preset veryslow -profile:v baseline  -crf 23 -acodec aac -b:a 32k -strict -5 147fss.mp4
# -i 输入的视频文件
# -r 每一秒的帧数,一秒10帧大概就是人眼的速度
# -pix_fmt 设置视频颜色空间 yuv420p网络传输用的颜色空间 ffmpeg -pix_fmts可以查看有哪些颜色空间选择
# -vcodec  软件编码器,通用稳定
# -preset 编码机预设  编码机预设越高占用CPU越大 有十个参数可选 ultrafast superfast veryfast(录制视频选用) faster fast medium(默认) slow slower veryslow(压制视频时一般选用) pacebo
# -profile:v 压缩比的配置 越往左边压缩的越厉害,体积越小 baseline(实时通信领域一般选用,画面损失越大) Extended Main(流媒体选用) High(超清视频) High 10 High 4:2:2 High 4:4:4(Predictive)
# -level:v 对编码机的规范和限制针对不通的使用场景来操作,也就是不同分辨率设置不同的值
# -crf 码率控制模式 用于对画面有要求,对文件大小无关紧要的场景  0-51都可以选择 0为无损 一般设置18 - 28之间 大于28画面损失严重
# -acodec 设置音频编码器
# https://blog.csdn.net/lm_is_dc/article/details/90030838

'''
'''

import sys

import os
import threading
import platform
import pymysql


class ZipPictureOrVideo(object):
    """
    压缩图片、视频
    """
    def __init__(self, filePath, inputName, bitrate, resolution, outName=""):
        self.filePath = filePath  # 文件地址
        self.inputName = inputName  # 输入的文件名字
        self.outName = outName  # 输出的文件名字
        self.system_ = platform.platform().split("-", 1)[0]
        if self.system_ == "Windows":
            self.filePath = (self.filePath + "\\") if self.filePath.rsplit("\\", 1)[-1] else self.filePath
        elif self.system_ == "Linux":
            self.filePath = (self.filePath + "/") if self.filePath.rsplit("/", 1)[-1] else self.filePath
        self.fileInputPath = self.filePath + inputName
        self.fileOutPath = self.filePath + outName
        self.bitrate = bitrate
        self.resolution = resolution

    def compress_video(self):
        """
        压缩视频

        :return:
        """
        fpsize = os.path.getsize(self.fileInputPath) / 1024
        if self.outName:
            compress = "ffmpeg -i {} -vcodec libx264 -b:v {}k -s {} {}".format(
                self.fileInputPath, self.bitrate, self.resolution, self.fileOutPath)
            isRun = os.system(compress)
        else:
            compress = "ffmpeg -i {} -vcodec libx264 -b:v {}k -s {} {}".format(
                self.fileInputPath, self.bitrate, self.resolution, self.fileInputPath)
            isRun = os.system(compress)
        if isRun != 0:
            return (isRun, "没有安装ffmpeg,在Linux使用【apt install ffmpeg】安装,windows去【ffmpeg】官网下载")
        return True


    def start_compress_video(self, is_async=True):
        """
        开始压缩视频
        :param is_async: 是否为异步压缩,默认为TRue
        :return:
        """
        if is_async:
            # 异步保存打开下面的代码,注释同步保存的代码
            thr = threading.Thread(target=self.compress_video)
            thr.start()
        else:
            # 下面为同步代码
            self.compress_video()

#打开数据库连接
conn = pymysql.connect(host='127.0.0.1',
                       user = "root",
                       password = "password",
                       database = "video",
                       port=3308)
                       
with conn:
    with conn.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `url`, `compress_bitrate`, `compress_resolution` FROM `video` WHERE `compress`=%s ORDER BY id DESC LIMIT 10"
        cursor.execute(sql, ('1',))
        results = cursor.fetchall()
        for result in results:
            url=result[1]+'_compress.mp4'
            
            file = ZipPictureOrVideo('Uploads', result[1], result[2], result[3], url)
            file.start_compress_video(False)
            
            id=int(result[0])
            sql_update = "UPDATE video SET compress = 2,ext='mp4',url='%s' WHERE id = %d" % (url, id,)
        
            cursor.execute(sql_update)
            print(result)
        
        conn.commit()