working mutple images and audio equal time.
import os
from moviepy.editor import ImageClip, AudioFileClip, concatenate_videoclips
def merge_images_and_audio(content_folder, audio_path, output_path):
"""
Creates a video from all images in a folder, with each image displayed
for an equal duration based on the audio's total duration.
Args:
content_folder: Path to the folder containing image files.
audio_path: Path to the audio file.
output_path: Path to the output video file.
"""
try:
# Load the audio file
audio_clip = AudioFileClip(audio_path)
# Get all image files in the folder
image_files = [
os.path.join(content_folder, f)
for f in os.listdir(content_folder)
if f.lower().endswith((".png", ".jpg", ".jpeg"))
]
if not image_files:
raise ValueError("No image files found in the specified folder.")
# Calculate the duration for each image
num_images = len(image_files)
image_duration = audio_clip.duration / num_images
# Create a list of ImageClips with the calculated duration
image_clips = []
for image_file in image_files:
image_clip = ImageClip(image_file)
image_clip = image_clip.set_duration(image_duration)
image_clip = image_clip.resize(height=480) # Resize to 480p
# Ensure both width and height are divisible by 2
width, height = image_clip.size
new_width = width + (width % 2) # Increment width if not divisible by 2
new_height = height + (height % 2) # Increment height if not divisible by 2
if (new_width, new_height) != (width, height):
image_clip = image_clip.resize(newsize=(new_width, new_height))
image_clips.append(image_clip)
# Concatenate all image clips
video_clip = concatenate_videoclips(image_clips, method="compose")
# Set the fps (frames per second) for the concatenated clip
video_clip.fps = 24 # Define a default fps value
# Set the audio to the concatenated video
video_clip = video_clip.set_audio(audio_clip)
# Write the final video to the output file
video_clip.write_videofile(
output_path,
codec='libx264',
audio_codec='aac',
threads=4,
fps=24, # Explicitly pass the fps value
ffmpeg_params=['-crf', '23', '-preset', 'fast', '-pix_fmt', 'yuv420p']
)
print(f"Video saved successfully at {output_path}")
except Exception as e:
print(f"Error occurred: {e}")
# Example usage:
content_folder = '/content' # Path to the folder with image files
audio_path = os.path.join(content_folder, 'సిరిధాన్యాలు పసందైన వంటకంబు_audio.mp3') # Replace with your actual audio file name
output_path = os.path.join(content_folder, 'సిరిధాన్యాలు పసందైన వంటకంబు_audio.mp4') # Output video path
# Call the function to merge images and audio into a video
merge_images_and_audio(content_folder, audio_path, output_path)