CodeGym /Courses /Python SELF EN /Creating and Working with Video and Audio Clips: Adding S...

Creating and Working with Video and Audio Clips: Adding Sound and Exporting Video with Audio

Python SELF EN
Level 47 , Lesson 1
Available

1. Video Clips and Audio Clips

Welcome to the lecture where we’ll become real video wizards and learn how to mix visuals and sounds, turning it into magic. Of course, using Python and the MoviePy library! Today’s goal is to learn how to work with video and audio clips, add soundtracks to videos, and export the result into an elegant file.

So, let’s grab some patience, be ready for a fun ride, and off we go—towards video editing greatness with Python!

Let’s start with the basics—creating video clips. Like true maestros, we must know how to extract frames from videos, add audio to them, and, of course, be able to export it all. MoviePy is perfect for this task.

Main Classes for Working with Video and Audio Clips

In MoviePy, the main classes for working with multimedia are:

  • VideoFileClip — for creating and working with video clips.
  • AudioFileClip — for working with audio clips.

Creating a Video Clip Object

First, we’ll create a video clip using the VideoFileClip class. It allows you to open a video file and access various editing parameters and methods.


from moviepy.editor import VideoFileClip

# Open a video file and create a video clip
video_clip = VideoFileClip("sample_video.mp4")

# Output video clip information
print("Video duration:", video_clip.duration, "seconds")
print("Video dimensions:", video_clip.size)

In this example:

  • VideoFileClip("sample_video.mp4") opens the video file and creates the video_clip object, which can be used to add sound and make other edits.
  • video_clip.duration and video_clip.size provide info about the video duration and size.

Creating an Empty Video Clip

Sometimes, you need to start with a blank slate—creating a clip from scratch. MoviePy makes this super easy with the ColorClip class.


from moviepy.editor import ColorClip

# Create a red clip with 640x360 dimensions and 5 seconds duration
blank_clip = ColorClip(size=(640, 360), color=[255, 0, 0], duration=5)

blank_clip.write_videofile("blank_clip.mp4", fps=25)

That will create a 5-second red video. Simple, but potentially very promising!

Extracting Audio from a Video Clip

First, let’s extract audio from an already loaded video clip. This is handy if you like the original soundtrack and want to use it separately.


# Extract audio from video
audio = video.audio

# Save audio to a file
audio.write_audiofile("extracted_audio.mp3")

Now you’ve got an audio file from your video. Handy when you just need the sound!

Creating an Audio Clip Object

MoviePy also lets you add audio clips. For this, you’ll use the AudioFileClip class, which opens the audio file and works similarly to video clips.


from moviepy.editor import AudioFileClip

# Open an audio file and create an audio clip
audio_clip = AudioFileClip("background_music.mp3")

# Output audio duration info
print("Audio duration:", audio_clip.duration, "seconds")

2. Editing Video and Audio Clips

Adding Audio to Video

Now that we have a video clip and an audio clip, we can combine them by adding a soundtrack to the video. In MoviePy, this is done with the set_audio() method.


# Add audio clip to video clip
video_with_audio = video_clip.set_audio(audio_clip)

This code creates a new object video_with_audio, where the audio clip audio_clip is integrated into the video clip video_clip.

Adjusting Audio Clip Duration

Sometimes, the durations of the audio clip and the video clip may differ. To match the audio clip to the video, you can use the subclip() method to trim the audio, or loop the audio to match the video’s length.

Trimming the Audio Clip to Fit the Video


# Trim the audio clip to match the video duration
audio_clip_trimmed = audio_clip.subclip(0, video_clip.duration)

# Add the trimmed audio to the video
video_with_audio = video_clip.set_audio(audio_clip_trimmed)

In this example:

  • audio_clip.subclip(0, video_clip.duration) creates a new audio clip trimmed to match the video clip’s duration.
  • The set_audio() method adds the trimmed audio to the video clip.

Looping the Audio Clip to Match the Video

If you want the audio clip to repeat until the video ends, use the fx() method with the loop function.


from moviepy.audio.fx.all import loop

# Loop the audio clip to match the video duration
audio_clip_looped = loop(audio_clip, duration=video_clip.duration)

# Add the looped audio to the video
video_with_audio = video_clip.set_audio(audio_clip_looped)

In this example:

  • loop(audio_clip, duration=video_clip.duration) creates a looped audio clip that repeats until the video finishes.
  • We add the looped audio to the video using set_audio().

3. Exporting Video with Added Audio

Exporting a Video Clip with Audio

Make sure you’ve got the necessary codecs, like libx264 for video and aac for audio, otherwise, no one’s going to see your stunning creation.

When exporting the video, you can specify various parameters, like resolution and frame rate:


# Export video with updated settings
video_with_audio.write_videofile(
    "output_video_with_audio.mp4",
    codec='libx264',
    audio_codec='aac',
    fps=30,
    preset='medium',
    bitrate="2000k"
)

In this example:

  • write_videofile("output_video_with_audio.mp4", codec="libx264", audio_codec="aac") saves the video with audio in MP4 format using the libx264 video codec and aac audio codec.

Tada! Your masterpiece is ready to upload to YouTube, Vimeo, or simply share with friends.

After adding the soundtrack to a video, you can export the result as a new file using the write_videofile() method.

Setting the Volume Level of the Audio Clip

To adjust the audio volume in the video, you can use the volumex() method to change the volume by a specific factor. For example, to make the sound quieter, specify a value less than 1, and to increase the volume, use a value greater than 1.

Example: Reducing Audio Volume


# Reduce audio clip volume by half
audio_clip_quieter = audio_clip.volumex(0.5)

# Add the quieter audio to the video
video_with_audio = video_clip.set_audio(audio_clip_quieter)
video_with_audio.write_videofile("output_video_quieter.mp4")

In this example:

  • audio_clip.volumex(0.5) reduces the audio volume to 50% of the original.
  • set_audio() and write_videofile() add this audio to the video and save the result.

4. Complete Example

Creating a Video with Audio and Adjusted Settings

Now, let’s combine all the steps into one example where we’ll add audio to a video, trim it to the desired duration, adjust the volume, and export the final video.


from moviepy.editor import VideoFileClip, AudioFileClip
from moviepy.audio.fx.all import loop

# Open the video file
video_clip = VideoFileClip("sample_video.mp4")

# Open the audio file
audio_clip = AudioFileClip("background_music.mp3")

# Adjust the audio volume
audio_clip_adjusted = audio_clip.volumex(0.7)

# Loop the audio to match the video duration
audio_clip_looped = loop(audio_clip_adjusted, duration=video_clip.duration)

# Add the audio to the video
video_with_audio = video_clip.set_audio(audio_clip_looped)

# Export the video with audio
video_with_audio.write_videofile("final_output_with_audio.mp4", codec="libx264", audio_codec="aac")

In this example:

  1. We load the video and audio files.
  2. Adjust the audio volume using volumex().
  3. Loop the audio to cover the video duration.
  4. Add the audio to the video.
  5. Export the video with added audio as final_output_with_audio.mp4.

Common Errors and Fixes

While working with MoviePy, some errors (like annoying bugs) might ruin your creative flow. For instance, issues with audio codecs or file format incompatibility. Use audio_codec='aac' for modern audio encoding—it solves a lot.

If your video or audio fails to export even though the code looks correct, check if you’ve got the required codecs installed. Download or update FFMPEG, which MoviePy uses as its engine for handling video and audio.

Now that you know how to create and export videos, the possibilities are endless. These skills can be useful in various projects—from creating tutorials to marketing materials. And at job interviews, the ability to automate video tasks could be your ace. In everyday work, it can save tons of time when dealing with multimedia content.

It’s time to unleash the magic of programming and creativity, and impress the world with your video clips. And remember, as one wise programmer said: "If the code doesn’t work, add more caffeine; if it does—add more flair!"

1
Task
Python SELF EN, level 47, lesson 1
Locked
Opening and analyzing a video file
Opening and analyzing a video file
2
Task
Python SELF EN, level 47, lesson 1
Locked
Creating and Saving an Empty Video Clip
Creating and Saving an Empty Video Clip
3
Task
Python SELF EN, level 47, lesson 1
Locked
Adding a soundtrack to a video
Adding a soundtrack to a video
4
Task
Python SELF EN, level 47, lesson 1
Locked
Creating a video with looped audio
Creating a video with looped audio
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION