Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop a mp4 file in moviepy?

My current code is taking a mp4 video file, it adds a mp3 music file to it, the duration of the mp4 file is set to the length of the mp3 file, the clip is resized to 1920x1080 pixels and finally it saves and outputs the finished video.

Result: The finished video plays the mp4 file one time and then freezes until the mp3 file ends.

Result that I want: How can I make the mp4 file loop until the end of the mp3 file so it doesn't freeze after one play.


from moviepy.editor import *
import moviepy.editor as mp
import moviepy.video.fx.all as vfx


audio = AudioFileClip("PATH/TO/MP3_FILE")

clip = VideoFileClip("PATH/TO/MP4_FILE").set_duration(audio.duration)


# Set the audio of the clip
clip = clip.set_audio(audio)

#Resizing
clip_resized = clip.resize((1920, 1080)) 


#Code that doesn't work for looping
newClip = vfx.loop(clip_resized)


# Export the clip
clip_resized.write_videofile("movie_resized.mp4", fps=24)

The code itself works but the mp4 doesn't loop until the end. Thanks in advance.

like image 773
Maximilian Freitag Avatar asked Nov 19 '25 00:11

Maximilian Freitag


1 Answers

3 Years late on that one, but it's still the top result for this on google.

If you want to loop it for the duration of audio, moviepy has a simple loop function that you call from the clip you want to loop, it takes either the amount of loops or the duration of time to loop for.

So in your case it would be

loopedClip = clip_resized.loop(duration = audio.duration)

Or if you don't want to create a seperate clip then

clip_resized = clip_resized.loop(duration = audio.duration)
like image 113
Bandit Avatar answered Nov 20 '25 14:11

Bandit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!