DEV Community

Md Morshedul Islam
Md Morshedul Islam

Posted on

Adding a Single Audio to Multiple Videos using Python and MoviePy

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
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Process each video

Loop over videos and do the following for each video:

  1. Get the absolute path of the video and define the absolute path of the output video.
  2. Load the clip to the program using the moviepy module.
  3. 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.
  4. 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()
Enter fullscreen mode Exit fullscreen mode

That's it! Adding sound to your videos is now just a few lines of Python code away. Happy coding!

Top comments (1)

Collapse
 
ridi profile image
Saika

helpful blog!๐Ÿ’–