I am trying to reduce the file size of a .mp4 file using the following code:
import os
import moviepy.editor as mp
import ffmpeg
def compress_video(input_file, output_file, target_size_ratio=0.5):
if not os.path.exists(input_file):
raise FileNotFoundError(f"Input file not found: {input_file}")
if target_size_ratio <= 0 or target_size_ratio >= 1:
raise ValueError("Target size ratio must be between 0 and 1")
# Get input video information
probe = ffmpeg.probe(input_file)
video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
bitrate = int(video_stream['bit_rate'])
# Calculate new bitrate to achieve the target file size
new_bitrate = int(bitrate * target_size_ratio)
# Load the video and compress
input_video = mp.VideoFileClip(input_file)
input_video.write_videofile(
output_file,
bitrate=f"{new_bitrate}k",
codec="libx264",
audio_codec="aac",
threads=4,
ffmpeg_params=["-strict", "-2"]
)
input_file = r"C:\Users\Hamid\Downloads\A.mp4"
output_file = r"C:\Users\Hamid\Downloads\B.mp4"
compress_video(input_file, output_file, target_size_ratio=0.5)
But I am getting the following error:
FileNotFoundError: [WinError 2] The system cannot find the file specified
Just a note I have a file in that directory called A.mp4 but currently no file exists called B.mp4.