視頻傳生活或者工作中很常見,如發送視頻郵件、在線視頻播放、視頻上傳下載等。未壓縮的大內存視頻文件傳輸時,不僅會消耗大量的網絡帶寬資源,還會使傳輸時間大幅增加。在網速有限的情況下,發送一個幾 GB 的未壓縮視頻可能需要數小時甚至更長時間;而壓縮后的視頻,傳輸時間會大幅縮短,用戶體驗得到顯著提升。對于在線視頻平臺,壓縮視頻能降低服務器壓力,使更多用戶可以流暢觀看視頻,減少卡頓現象。
下面是一個使用 FFmpeg 壓縮視頻文件的 Python 腳本,你可以使用它來減小視頻文件的大小。
使用說明:
1. 首先需要安裝FFmpeg:
? ?- Windows: 從瀏覽器中下載并添加到系統PATH
? ?- macOS: 使用Homebrew安裝 `brew install ffmpeg`
? ?- Linux: 使用包管理器安裝 `sudo apt-get install ffmpeg` 或 `sudo yum install ffmpeg`
2. 安裝必要的Python依賴:
?
?```
? ?pip install argparse
? ?```
示例代碼:
import os
import argparse
import subprocess
import sys
from pathlib import Pathdef compress_video(input_file, output_file=None, quality=28, codec="libx264", crf_min=18, crf_max=32):"""使用FFmpeg壓縮視頻文件參數:input_file: 輸入視頻文件路徑output_file: 輸出視頻文件路徑,默認為輸入文件名添加_compressed后綴quality: 視頻質量,使用CRF值(18-32),值越高文件越小,默認為28codec: 視頻編碼格式,默認為libx264(h.264)crf_min: 最小CRF值限制crf_max: 最大CRF值限制"""# 確保輸入文件存在if not os.path.isfile(input_file):print(f"錯誤: 輸入文件不存在 - {input_file}")return False# 限制CRF值范圍quality = max(crf_min, min(crf_max, quality))# 生成輸出文件名(如果未指定)if not output_file:base_name, ext = os.path.splitext(input_file)output_file = f"{base_name}_compressed{ext}"# 構建FFmpeg命令cmd = ["ffmpeg","-i", input_file,"-c:v", codec,"-crf", str(quality),"-preset", "medium", # 編碼速度與壓縮比的平衡"-c:a", "aac", # 音頻編碼"-b:a", "128k", # 音頻比特率"-y", # 覆蓋已存在文件output_file]try:# 執行FFmpeg命令print(f"開始壓縮視頻: {input_file}")print(f"輸出文件: {output_file}")print(f"使用CRF: {quality}")result = subprocess.run(cmd, capture_output=True, text=True, check=True)# 檢查源文件和壓縮后文件的大小original_size = os.path.getsize(input_file)compressed_size = os.path.getsize(output_file)reduction_percentage = (1 - compressed_size / original_size) * 100print(f"壓縮完成!")print(f"原始大小: {original_size / (1024 * 1024):.2f} MB")print(f"壓縮后大小: {compressed_size / (1024 * 1024):.2f} MB")print(f"減少比例: {reduction_percentage:.2f}%")return Trueexcept subprocess.CalledProcessError as e:print(f"壓縮失敗: {e.stderr}")return Falseexcept Exception as e:print(f"發生錯誤: {str(e)}")return Falsedef batch_compress(directory, quality=28, codec="libx264"):"""批量壓縮目錄中的所有視頻文件參數:directory: 目錄路徑quality: 視頻質量CRF值codec: 視頻編碼格式"""if not os.path.isdir(directory):print(f"錯誤: 目錄不存在 - {directory}")return# 支持的視頻文件擴展名video_extensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv']compressed_count = 0total_files = 0# 統計總視頻文件數for filename in os.listdir(directory):if any(filename.lower().endswith(ext) for ext in video_extensions):total_files += 1print(f"發現 {total_files} 個視頻文件")# 處理每個視頻文件for i, filename in enumerate(os.listdir(directory)):if any(filename.lower().endswith(ext) for ext in video_extensions):input_path = os.path.join(directory, filename)print(f"\n({i+1}/{total_files}) 處理文件: {filename}")if compress_video(input_path, quality=quality, codec=codec):compressed_count += 1print(f"\n批量壓縮完成! 共處理 {total_files} 個文件,成功壓縮 {compressed_count} 個文件")def main():"""命令行入口函數"""parser = argparse.ArgumentParser(description='視頻壓縮工具 - 使用FFmpeg壓縮視頻文件')parser.add_argument('--input', '-i', help='輸入視頻文件路徑或目錄')parser.add_argument('--output', '-o', help='輸出視頻文件路徑(僅當輸入為單個文件時有效)')parser.add_argument('--quality', '-q', type=int, default=28, help='視頻質量(18-32),值越高文件越小,默認28')parser.add_argument('--batch', '-b', action='store_true', help='批量壓縮目錄中的所有視頻文件')parser.add_argument('--codec', '-c', default='libx264', help='視頻編碼格式,默認為libx264(h.264)')args = parser.parse_args()# 檢查是否安裝了FFmpegtry:subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)except (subprocess.SubprocessError, FileNotFoundError):print("錯誤: 未找到FFmpeg。請先安裝FFmpeg并確保其在系統PATH中。")print("FFmpeg下載地址: https://ffmpeg.org/download.html")sys.exit(1)if not args.input:print("錯誤: 必須指定輸入文件或目錄")parser.print_help()returnif args.batch:batch_compress(args.input, args.quality, args.codec)else:# 單文件轉換if os.path.isfile(args.input):compress_video(args.input, args.output, args.quality, args.codec)else:print("錯誤: 輸入文件不存在")if __name__ == "__main__":main()
3. 基本用法:
? ?- 壓縮單個視頻:`python video_compressor.py -i input.mp4 -o output.mp4`
? ?- 批量壓縮目錄中的所有視頻:`python video_compressor.py -i /path/to/videos -b`
? ?- 調整壓縮質量(CRF值,18-32,值越高文件越小):`python video_compressor.py -i input.mp4 -q 30`
4. 其他選項:
? ?- 指定視頻編碼格式:`-c libx265`(更高壓縮率,但可能需要更長時間)
? ?- 查看幫助信息:`python video_compressor.py --help`
腳本會自動計算并顯示壓縮前后的文件大小和減少比例,方便你了解壓縮效果。
如果我們覺得代碼的方式比較麻煩,可以使用“匯幫超級壓縮器”來壓縮視頻文件。小白也能操作的方法。
學習視頻文件壓縮方法的過程,也是提升自身數字技能和數據處理能力的過程。掌握壓縮方法后,能進一步理解視頻編碼、格式轉換等相關知識,為學習更復雜的視頻編輯、特效制作等技能打下基礎。這種能力的提升,在數字化時代的各個領域都能發揮作用,無論是工作中的數據處理,還是個人對數字信息的管理和利用,都能更加得心應手。