I am uploading text and videos to a site by Python program. This site says they only receive video files of up to 50 MB in size. Otherwise, they will reject the video and other associated information.
To ensure I can send video continuously, I want to compress it to target size (e.g. 50 MB) before sending. Because no loss of quality is impossible, it is ok to have moderate clarity loss in video or audio.
Is there any elegant way in Python for this purpose? Thanks!
Compress video files by Python and FFmpeg
Tools
FFmpeg is a powerful tool for video editing. And there is a great Python binding named ffmpeg-python (API Reference) for this. Firstly,
pip install ffmpeg-python
and install FFmpeg.Steps
Probe the configuration of video by function
ffmpeg.probe()
to get duration, audio & video bit rate and so on. And calculate the bit rate of the target file based on what we have. Then, construct commands byffmpeg.input()
andffmpeg.output()
. Finally, run it.Codes
Following is the example code. Change the compression algo for your situation if you want. For easy follow-up, I hided the code of boundary condition. The code I am using is in GitHub Gist. Any bug report is welcomed!
Notes
Don't waste your time! Judge the file size before compressing.
You can disable two-pass function by only keeping second
ffmpeg.output()
without parameter'pass': 2
.If video bit rate < 1000, it will throw exception
Bitrate is extremely low
.The biggest min file size I recommend is: