MoviePy is a Python module used for video editing. You can automate many video editing tasks using this library. In this blog, we will explore how to add sound to silent(or noisy) video(s).
Make sure you have Python installed, and install the moviepy
library using the following command:
pip install moviepy
Scenario: We have a folder with multiple videos and an audio track to add to all of these videos. If the video length is greater than audio the the audio will loop otherwise trim. We will save the output to another folder.
Reading videos and audio track
video_files = [f for f in os.listdir(video_folder_path) if f.endswith('.mp4')]
audio_clip = AudioFileClip(audio_path)
Process each video
Loop over videos and do the following for each video:
- Get the absolute path of the video and define the absolute path of the output video.
- Load the clip to the program using the
moviepy
module. - Check if the video length is greater than the video length then clip the audio otherwise loop the audio to fit in the video length.
- Save and Close the video. Done!
for video_file in video_files:
# Specify the paths for the current video and output video
video_path = os.path.join(video_folder, video_file)
output_path = os.path.join(output_folder, video_file)
# Load the video clip
video_clip = VideoFileClip(video_path)
# Trim or loop the audio to match the duration of the video
if audio_clip.duration > video_clip.duration:
# Trim the audio to match the duration of the video
audio_clip_processed = audio_clip.subclip(0, video_clip.duration)
else:
# Loop the audio to cover the entire video duration
audio_clip_processed = audio_clip.volumex(video_clip.duration // audio_clip.duration + 1)
# Set the video clip's audio to be the modified audio
video_clip = video_clip.set_audio(audio_clip_processed)
# Write the final video with audio using different codec options
video_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
# Close the current video clip
video_clip.close()
audio_clip.close()
That's it! Adding sound to your videos is now just a few lines of Python code away. Happy coding!
Top comments (1)
helpful blog!💖