import cv2
from moviepy.editor import VideoFileClip
from pydub import AudioSegment
import os
input_video = "file name.mp4" # Replace with the name of your video file
output_dir = "output"
segment_duration = 540 # 9 minutes in seconds
cap = cv2.VideoCapture(input_video)
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
aspect_ratio = 9 / 16
output_counter = 1
print("Processing video started...")
while True:
ret, frame = cap.read()
if not ret:
break
if frame_width / frame_height > aspect_ratio:
new_width = int(frame_height * aspect_ratio)
left = (frame_width - new_width) // 2
right = left + new_width
new_frame = frame[:, left:right]
else:
new_height = int(frame_width / aspect_ratio)
top = (frame_height - new_height) // 2
bottom = top + new_height
new_frame = frame[top:bottom, :]
video_clip = VideoFileClip(input_video).subclip((output_counter - 1) * segment_duration, output_counter * segment_duration)
audio_clip = video_clip.audio
output_dir = "output/"
if not os.path.exists(output_dir):
os.makedirs(output_dir)
video_clip.write_videofile(os.path.join(output_dir, f"output{output_counter}.mp4"), codec="libx264", audio=False)
audio_clip.write_audiofile(os.path.join(output_dir, f"audio{output_counter}.mp3"))
output_counter += 1
print(f"Segment {output_counter} generated...")
cap.release()
print("Video processing finished.")