Created
November 8, 2024 12:20
-
-
Save fffiloni/07cbacf2cb5dc59d0e926a8054b22840 to your computer and use it in GitHub Desktop.
Python - Convert a video to universal codecs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from moviepy.editor import VideoFileClip | |
import os | |
def convert_video_to_h264_aac(video_path): | |
# Get the directory and original filename | |
original_dir = os.path.dirname(video_path) | |
original_name, _ = os.path.splitext(os.path.basename(video_path)) | |
# Define the output path in the same directory | |
output_path = os.path.join(original_dir, f"{original_name}_converted.mp4") | |
# Load the video | |
with VideoFileClip(video_path) as video: | |
# Check if video has an audio track | |
if video.audio: | |
# Convert video with H.264 and AAC audio | |
video.write_videofile( | |
output_path, | |
codec="libx264", # H.264 video codec | |
audio_codec="aac", # AAC audio codec for compatibility | |
temp_audiofile="temp-audio.m4a", # Temporary audio file for processing | |
remove_temp=True # Remove temporary audio file after saving | |
) | |
else: | |
# Convert video without audio | |
video.write_videofile( | |
output_path, | |
codec="libx264", # H.264 video codec | |
audio=False # No audio in output if original video has no audio | |
) | |
return output_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment