How to end a video when audio ends with moviepy?

Viewed 512

I am using this code to add an audio file to a video file in Python, but, when video ends, the audio keeps playing until the end. I want to end when the video ends.

Any suggestion?

from moviepy.editor import *
videoclip = VideoFileClip(filename)
audioclip = AudioFileClip("audio.mp3")

new_audioclip = CompositeAudioClip([audioclip])
videoclip.audio = new_audioclip
videoclip.write_videofile("new_filename.mp4")
2 Answers

Instead of CompositeAudioClip, afx works for me:

from moviepy.editor import *

videoclip = VideoFileClip(filename)
audioclip = AudioFileClip("audio.mp3")

new_audio = afx.audio_loop(audioclip, duration=videoclip.duration)
videoclip.audio = new_audio
videoclip.write_videofile("new_filename.mp4")

You should get video duration (length) and use it to crop audio.

And you don't need CompositeAudioClip for this.

from moviepy.editor import *

videoclip = VideoFileClip(filename)
audioclip = AudioFileClip("audio.mp3")

videoclip.audio = audioclip.set_duration(videoclip.duration)

videoclip.write_videofile("new_filename.mp4")
Related