mp3 image worked on 10thdec 24 2019
import os
from moviepy.editor import ImageClip, AudioFileClip, CompositeVideoClip
def merge_image_and_audio(image_path, audio_path, output_path):
"""Merges an image and an audio file into a video with 480p resolution and audio duration match.
Args:
image_path: Path to the image file.
audio_path: Path to the audio file.
output_path: Path to the output video file.
"""
try:
# Load the image and audio files
image_clip = ImageClip(image_path)
audio_clip = AudioFileClip(audio_path)
# Set image duration to match audio duration
image_clip = image_clip.set_duration(audio_clip.duration)
# Resize the image to 480p resolution (height=480) and ensure width is divisible by 2
image_clip = image_clip.resize(height=480)
# Ensure width is divisible by 2
width, height = image_clip.size
if width % 2 != 0:
image_clip = image_clip.resize(width=width + 1) # Adjust width if needed
# Set the FPS (frames per second) for the video
image_clip = image_clip.set_fps(24)
# Create a composite video clip with the image and audio
video_clip = CompositeVideoClip([image_clip])
video_clip = video_clip.set_audio(audio_clip)
# Write the video to the output file with additional ffmpeg parameters for compatibility
video_clip.write_videofile(output_path, codec='libx264', audio_codec='aac', threads=4,
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 content folder in Google Colab
image_path = os.path.join(content_folder, 'image.png') # Replace with your actual image file name
audio_path = os.path.join(content_folder, 'audio.mp3') # Replace with your actual audio file name
output_path = os.path.join(content_folder, 'output_video.mp4') # Output video path
# Call the function to merge image and audio into a video
merge_image_and_audio(image_path, audio_path, output_path)