简体   繁体   English

如何在moviepy中循环播放mp4文件?

[英]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.我当前的代码正在获取一个 mp4 视频文件,它向其中添加了一个 mp3 音乐文件,将 mp4 文件的持续时间设置为 mp3 文件的长度,将剪辑调整为 1920x1080 像素,最后保存并输出完成视频。

Result: The finished video plays the mp4 file one time and then freezes until the mp3 file ends.结果:完成的视频播放 mp4 文件一次,然后冻结,直到 mp3 文件结束。

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.我想要的结果:我怎样才能让 mp4 文件循环到 mp3 文件的结尾,这样它就不会在一次播放后冻结。


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.代码本身有效,但 mp4 直到最后才会循环。 Thanks in advance.提前致谢。

3 Years late on that one, but it's still the top result for this on google.那个晚了 3 年,但它仍然是谷歌上的最佳结果。

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.如果您想在音频的持续时间内循环播放,moviepy 有一个简单的循环功能,您可以从要循环的剪辑中调用它,它需要循环次数或循环持续时间。

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)

If you get this error:如果您收到此错误:

OSError: Error in file...video.mp4, Accessing time t=101.77-101.81 seconds, with clip duration=101 seconds, OSError:文件中的错误...video.mp4,访问时间 t=101.77-101.81 秒,剪辑持续时间=101 秒,

This problem occured because the loop do not match with the audio of the final looped video file出现此问题是因为循环与最终循环视频文件的音频不匹配

So you have to extract the audio from the video file (or your custom audio file) and loop it too as the video file因此,您必须从视频文件(或您的自定义音频文件)中提取音频并将其作为视频文件循环播放

    audio = AudioFileClip("video.mp4")#here i'm using the audio of the original video but if you have custom audio pass it here
    audio = afx.audio_loop(audio, duration=500) #you can use n=X too 
    clip1 = VideoFileClip("video.mp4")
    clip1 = vfx.loop(clip1, duration=500) #you can use n=X too 
    clip1 = clip1.set_audio(audio)
    clip1.write_videofile("movie.mp4")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM