images plus mp3 to mp4 generate code , working
!pip install pydub
!apt-get install ffmpeg
from moviepy.editor import ImageClip, concatenate_videoclips, AudioFileClip
import os
from pydub import AudioSegment # We will use pydub to convert audio files
# Function to convert audio to WAV format using pydub (if needed)
def convert_audio_to_wav(audio_path):
if audio_path.endswith('.mp3'):
audio = AudioSegment.from_mp3(audio_path)
wav_path = audio_path.replace('.mp3', '.wav')
audio.export(wav_path, format="wav")
return wav_path
return audio_path # If it's already WAV, return as is
# Function to create a video
def create_video_with_audio(image_list, durations, audio_path, output_path):
try:
# Convert audio to WAV if it's in MP3 format
audio_path = convert_audio_to_wav(audio_path)
# Load the audio file
audio_clip = AudioFileClip(audio_path)
audio_duration = audio_clip.duration
# Generate video clips for each image with the specified duration
video_clips = []
for image, duration in zip(image_list, durations):
clip = ImageClip(image).set_duration(duration)
clip = clip.resize(height=720) # Resize the images to a fixed height, maintaining aspect ratio
video_clips.append(clip)
# Concatenate video clips
final_video = concatenate_videoclips(video_clips, method="compose")
# Set the audio to the video
final_video = final_video.set_audio(audio_clip)
# Write the video file to the output path
final_video.write_videofile(
output_path,
codec="libx264", # Ensure H.264 encoding
fps=24, # Frames per second
audio_codec="aac", # Ensure AAC audio encoding
threads=4 # Use multiple threads for faster processing
)
print(f"Video saved successfully at {output_path}")
except Exception as e:
print(f"Error occurred: {e}")
# Inputs
content_folder = "/content"
output_video_path = os.path.join(content_folder, "output_video.mp4")
audio_file = os.path.join(content_folder, "audio.mp3")
# Get list of image files from the content folder
image_list = sorted(
[os.path.join(content_folder, img) for img in os.listdir(content_folder) if img.endswith(('.png', '.jpeg', '.jpg'))]
)
# If images are found, allow the user to specify durations
if len(image_list) > 0:
print("Found the following images:")
for idx, img in enumerate(image_list, start=1):
print(f"{idx}. {os.path.basename(img)}")
print("\nEnter the duration (in seconds) for each image as a comma-separated list.")
print("Example: If you have 3 images, enter durations like this: 5, 10, 8")
duration_input = input("Durations: ")
try:
durations = [float(d.strip()) for d in duration_input.split(',')]
if len(durations) != len(image_list):
raise ValueError("Number of durations must match the number of images.")
except Exception as e:
print(f"Invalid input: {e}")
print("Using default duration of 5 seconds for each image.")
durations = [5] * len(image_list)
else:
print("No images found in the content folder.")
durations = []
# Check if the audio file exists
if os.path.exists(audio_file) and len(image_list) > 0:
create_video_with_audio(image_list, durations, audio_file, output_video_path)
else:
print("Audio file is missing or no images are found.")
# it is working properly.