import os
import random
from moviepy.editor import VideoFileClip, concatenate_videoclips
import imageio_ffmpeg as ffmpeg
#!/usr/bin/env python
def create_initial_video(gen_num,total_duration):
total_duration = total_duration + 1
video_paths = []
path = 'presets/videos'
for i in os.listdir(path):
if i.lower().endswith(('mp4', 'mov', 'avi', 'mkv')): # Ensure valid video file extensions
video_paths.append(os.path.join(path, i))
random.shuffle(video_paths) # Randomize the order of video_paths
clips = []
cumulative_duration = 0
target_resolution = (1080, 1920) # Target resolution for Instagram and TikTok
for path in video_paths:
try:
video = VideoFileClip(path)
clip_duration = random.randint(1,3)
if clip_duration > video.duration:
clip_duration = video.duration
cumulative_duration += clip_duration
if cumulative_duration > total_duration:
clip_duration -= cumulative_duration - total_duration # Adjust to avoid exceeding total duration
if clip_duration > 0:
clip = video.subclip(0, clip_duration).without_audio()
clip = clip.resize(newsize=target_resolution) # Resize clip to target resolution
clips.append(clip)
if cumulative_duration >= total_duration:
break # Stop if we've reached the total duration
except Exception as e:
print(f"Error processing file {path}: {e}")
continue
if clips:
final_clip = concatenate_videoclips(clips, method="compose") # Ensure final duration is correct
# Add crossfade transitions between clips (optional)
# transitions_duration = 0.5 # Duration of crossfade transitions
# final_clip = concatenate_videoclips([clip.crossfadein(transitions_duration) for clip in clips], method="compose")
final_clip.write_videofile(f'presets/subinitialvideos/{gen_num}initial.mp4', codec="libx265", threads=16)
else:
print("No valid clips to create a final video.")
In this when i try to create like a 5s video it works but when i make the video 20s long it gives me this error:
Error processing file presets/videos/359vid.mp4: MoviePy error: failed to read the first frame of video file presets/videos/359vid.mp4. That might mean that the file is corrupted. That may also mean that you are using a deprecated version of FFMPEG. On Ubuntu/Debian for instance the version in the repos is deprecated. Please update to a recent version from the website.
So this is my code:
In this when i try to create like a 5s video it works but when i make the video 20s long it gives me this error: