The art of converting video files from one format to another is not a simple endeavor, yet with the aid of tools like Python and the MoviePy library, this task can be streamlined. Specifically, we will examine how to convert MP4 video files to AVI. MoviePy is a powerful Python library for video processing, which offers both basic functionality such as cutting and concatenation, as well as advanced functions for object tracking, composition, and special effects. In the context of our script, MoviePy is used to read video files and output the converted version. At the heart of our conversion script are just a few lines of code. We first import the necessary modules: os, a standard Python module that provides functions for interacting with the operating system, and VideoFileClip, a class from the MoviePy library used to represent a video. We then use the os.getcwd() method to get the path of the current directory. This is the directory from which the script is run. If you want to use a different directory, this value can be modified. We proceed then with os.listdir(directory) to get a list of all files in the specified directory. For each file, we check if the file name ends with ‘.mp4’, thus indicating it is an MP4 video. Finally, we use VideoFileClip to read the MP4 video. After reading the video, we use the write_videofile() method to write the converted file. The first parameter of the method is the path of the output file. We use os.path.splitext(filename) to get the name of the original file without the extension, then we add ‘.avi’ to create the name of the output file. The codec parameter specifies the codec to use for video encoding. ‘mpeg4’ is a common codec compatible with the AVI format.
from moviepy.editor import VideoFileClip
directory = os.getcwd()
for filename in os.listdir(directory):
video = VideoFileClip(os.path.join(directory, filename))
video.write_videofile(os.path.join(directory, os.path.splitext(filename) + '.avi'), codec='mpeg4', bitrate='4000k')
This script offers a simple method to convert all MP4 videos in a directory to AVI videos. Thanks to the use of MoviePy and Python’s file management functions, we are able to perform the conversion with a few lines of code. An important aspect to consider is that the conversion of video formats can involve a loss of quality, so it’s advisable to keep a copy of the original if quality is a concern. In case the generated AVI files present a low definition quality, it’s possible to improve this by setting a higher bitrate in the write_videofile() method, for instance ‘4000k’, but remember that a higher bitrate can lead to a larger file size.