Replace audio of a video in Python
In this short tutorial, we are going to learn how to Replace the audio of a video in Python that is how can we add another audio file to some video. It’s very simple just a few lines of code. Let’s see how it works.
For this task, we are going to use one of the python libraries which is Moviepy. MoviePy Python library is used to edit a video. We can perform operations such as cutting, splitting, merging, composition, etc.
Before proceeding towards our task let’s import this library into our system. Run the following line in your code editor.
import moviepy.editor as mp
Here we have imported the editor section of the moviepy library as mp. let’s see the further process. Here is the code.
#Input audio file audio = mp.AudioFileClip('Audio/file.mp3') #Input video file video = mp.VideoFileClip('Video/video.mp4') #adding external audio to video final_video = video.set_audio(audio) #Extracting final output video final_video.write_videofile("output_video.mp4")
First, we are giving our audio input file as input in a variable named audio. Then we are giving our video file as input in the video variable. AudioFileClip() and VideoFileClip() are two functions of Moviepy used for input purposes. Next, we are adding that audio file to our video using the set_audio() function which takes that audio file as a parameter.
Finally, we are extracting our output video file using the write_videofile() function which takes the parameter name of the output file we want to give. output_video.mp4 file is saved as an Output file. Here you can see how the output looks like.
Output [MoviePy] >>>> Building video output_video.mp4 [MoviePy] Writing audio in output_videoTEMP_MPY_wvf_snd.mp3 100%|██████████| 601/601 [00:01<00:00, 513.27it/s][MoviePy] Done. [MoviePy] Writing video output_video.mp4 100%|██████████| 3219/3219 [00:19<00:00, 162.82it/s] [MoviePy] Done. [MoviePy] >>>> Video ready: output_video.mp4
Also learn: Create video with images in Python