Many people know that there is a package of FFmpeg utilities that can be used to compress and convert video files. To convert a file from one format to another, it is enough to specify several keys, the path to the source file, the path to the output file and do it on the command line. If there are a lot of files or they are in subdirectories, then you can write a script. I will show an example of how this can be done in python.
This example demonstrates such technologies:
- Using the ffmpeg.exe utility to convert to the specified format.
- Recursively searches for files in a directory with a given extension.
- Executing an external utility from python using subprocess.run with passing parameters.
- Saving information to a log file as the script is executed for later control.
import os
import subprocess
FFMPEGDIR = 'd:\\Program Files\\ffmpeg\\bin\\' # downloaded from ffmpeg.org
BASEDIR = 'd:\\VIDEO\\' # Video files
def process_file(srcfile : str):
''' Process the source file '''
print(srcfile)
dstfile = os.path.splitext(srcfile)[0] + '.mp4' # Result file extension
subprocess.run([FFMPEGDIR + 'ffmpeg.exe',
'-i', srcfile, # Source video file
'-map_metadata', '0:s:0', # Keep metadata
'-c:v', 'libx264',
'-s', '960x540', # new resolution
'-crf', '27', # Video compress level. Higher - smallest bitrate
'-ab', '64K' , # Audio bitrate
'-y', # Rewrite if exists
dstfile])
return dstfile
def process_dirs(d):
''' Process all files in directory and subfolders '''
logfile = open('result.txt', 'a') # log
for address, dirs, files in os.walk(d):
for fname in files:
if (os.path.splitext(fname)[1]).lower()=='.mov':
dstfile = process_file(os.path.join(address,fname))
logfile.write(f'{dstfile} {str(os.path.getsize(dstfile)/1024/1024)}:.1fMb\n')
logfile.close() # log
if __name__ == '__main__':
process_dirs(BASEDIR)
The command line to convert each file looks like this:
ffmpeg.exe -i srcfile.mov -map_metadata 0:s:0 -c:v libx264 -s 960x540 -crf 27 -ab 64K -y dstfile.mp4