Spaces:
Sleeping
Sleeping
Upload img_audio_merge.py
Browse files11234567891011121314151617181956723248910111213141516171819202122232425262728from moviepy.editor import *
import ffmpeg
import os
def merge_audio_image(mp3_path, image_path, output_dir, unique_id):
# Load the image
image_clip = ImageClip(image_path)
# Load the audio
audio_clip = AudioFileClip(mp3_path)
# Set the duration of the image clip to match the audio duration
image_clip = image_clip.set_duration(audio_clip.duration)
# Resize the image clip to Instagram's square dimensions (1080, 1080)
image_clip = image_clip.resize((1080, 1080))
# Set the audio to the image clip
final_clip = image_clip.set_audio(audio_clip)
# Generate output file path
output_path = os.path.join(output_dir, f"{unique_id}.mp4")
# Write the output video file
final_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
# Ensure the image file exists
if not os.path.isfile(image_path):
raise FileNotFoundError(f"Image file not found: {image_path}")
# Ensure the audio file exists
if not os.path.isfile(mp3_path):
raise FileNotFoundError(f"Audio file not found: {mp3_path}")
# Create the ffmpeg command to combine image and audio into a video
(
ffmpeg
.input(image_path)
.filter('scale', size='1080x1080', force_original_aspect_ratio='decrease')
.pad('1080', '1080', -1, -1)
.input(mp3_path)
.output(output_path, vcodec='libx264', acodec='aac', strict='experimental', pix_fmt='yuv420p', shortest=None)
.run()
)
return output_path
img_audio_merge.py+19-18