Python 批量将 AVI 转换为 MP4 并删除源文件
使用 Python 和 FFmpeg 批量将 AVI 转换为 MP4 并删除源文件
本程序使用 Python 和 FFmpeg 将指定目录及其子目录下的所有 .avi 文件转换为同名的 .mp4 文件,并删除源 .avi 文件。如果对应的 .mp4 文件已经存在且视频长度与 .avi 文件相同,则跳过转换。转换完成后,会显示相应的进度信息,并删除 .avi 文件。
import os
import subprocess
import shutil
def convert_avi_to_mp4(avi_file, mp4_file):
# 使用 FFmpeg 将 avi 文件转换为 mp4 文件
subprocess.call(['ffmpeg', '-i', avi_file, '-c:v', 'copy', '-c:a', 'copy', mp4_file])
def get_video_length(file):
# 使用 FFmpeg 获取视频文件的长度(秒)
result = subprocess.Popen(['ffprobe', '-i', file, '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv=%s' % ('p=0')], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = result.communicate()[0]
return float(output)
def convert_directory(dir_path):
for root, dirs, files in os.walk(dir_path):
for file in files:
if file.endswith('.avi'):
avi_file = os.path.join(root, file)
mp4_file = os.path.splitext(avi_file)[0] + '.mp4'
if not os.path.exists(mp4_file) or get_video_length(mp4_file) != get_video_length(avi_file):
print(f'Converting {avi_file} to {mp4_file}...')
convert_avi_to_mp4(avi_file, mp4_file)
print(f'Conversion completed.')
# 删除 .avi 文件
os.remove(avi_file)
else:
print(f'{avi_file} already converted, skipping...')
if __name__ == '__main__':
directory_path = '/path/to/directory' # 替换为实际的目录路径
convert_directory(directory_path)
请将代码中的 /path/to/directory 替换为实际的目录路径。
运行程序时,将会遍历指定目录及其子目录下的所有 .avi 文件,如果对应的 .mp4 文件已经存在且视频长度与 .avi 文件相同,则跳过转换。转换完成后,会显示相应的进度信息,并删除 .avi 文件。
原文地址: https://www.cveoy.top/t/topic/oWo1 著作权归作者所有。请勿转载和采集!