Skip to content

Instantly share code, notes, and snippets.

@yalue
Created January 11, 2025 01:57
Show Gist options
  • Select an option

  • Save yalue/5af553744577519a51f63be4d0bd1da5 to your computer and use it in GitHub Desktop.

Select an option

Save yalue/5af553744577519a51f63be4d0bd1da5 to your computer and use it in GitHub Desktop.
Ruby snippet for reencoding .mp4 videos using ffmpeg
# Returns the file path with extension removed
def strip_extension(filepath)
File.join(
File.dirname(filepath),
File.basename(filepath, File.extname(filepath))
)
end
# Re-encodes the given file as .mp4 using libh264 and MP3 audio. Returns the
# filename of the new file.
def convert_video(filename)
new_name = strip_extension(filename) + ".mp4"
puts "Will convert #{filename} -> #{new_name}"
cmd = [
"ffmpeg",
"-y",
"-i",
filename,
"-map_metadata",
"0",
"-movflags",
"use_metadata_tags",
"-c:v",
"libx264",
"-preset",
"medium",
"-crf",
"22",
"-c:a",
"libmp3lame",
"-q:a",
"1",
new_name,
]
output = ""
IO.popen(cmd, "r", :err=>[:child, :out]) do |cmd_output|
output = cmd_output.read
end
puts "Conversion done; last 3 lines of stdout:"
puts output.split(/\n+/)[-3..].join("\n")
new_name
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment