Skip to content

Instantly share code, notes, and snippets.

@jaymcgavren
Created September 8, 2026 05:55
Show Gist options
  • Select an option

  • Save jaymcgavren/b13386c7a6dd192b08ed6f2d2d7eebba to your computer and use it in GitHub Desktop.

Select an option

Save jaymcgavren/b13386c7a6dd192b08ed6f2d2d7eebba to your computer and use it in GitHub Desktop.
A Ruby script that uses ffmpeg to mix an audio track into a video
#!/usr/bin/env ruby
# Mixes a sound file into the sound of a video. Both are heard at once, and the
# video keeps its own length. The sound file must not be longer than the video.
#
# video_audio_mix.rb -a music.m4a gameplay.mp4
# video_audio_mix.rb -a voice.wav --volume 30 gameplay.mp4 narrated.mp4
#
# Both sounds play at their own volume unless --volume lowers the video's sound
# to make room. If the video has no sound of its own, the file becomes its sound.
#
# The picture is copied, not re-encoded, so it loses no quality at all. Only the
# sound is made again.
require "json"
require "optparse"
require "shellwords"
ENCODE = %w[-c:v copy -c:a aac -b:a 192k]
DEFAULTS = { audio: nil, volume: 100 }
# Reads the options, and leaves the file names in argv.
def parse_options(argv)
options = DEFAULTS.dup
parser = OptionParser.new do |opt|
opt.banner = "Usage: video_audio_mix.rb -a SOUND [options] INPUT [OUTPUT]"
opt.on("-a", "--audio FILE", "the sound file to mix in") { |v| options[:audio] = v }
opt.on("-v", "--volume PERCENT", Integer, "how much of the video's own sound to keep (default: #{DEFAULTS[:volume]})") { |v| options[:volume] = v }
opt.on("-h", "--help") { puts opt; exit }
end
parser.parse!(argv)
abort parser.help if argv.empty? || options[:audio].nil?
abort "--volume takes 0 to 100" unless (0..100).cover?(options[:volume])
options
end
# Names the output after the input: clip.mp4 becomes clip.mixed.mp4.
def default_output(input)
extension = File.extname(input)
input.delete_suffix(extension) + ".mixed" + extension
end
# Asks ffprobe how long a file is and whether it has any sound.
def probe_media(path)
probe = `ffprobe -v error -show_entries stream=codec_type:format=duration -of json #{Shellwords.escape(path)}`
abort "could not read #{path}" unless $?.success?
probe = JSON.parse(probe)
sound = probe.fetch("streams").any? { |stream| stream["codec_type"] == "audio" }
[probe.fetch("format").fetch("duration").to_f, sound]
end
# Builds the filter graph. The sound file is padded with silence so that mixing
# it in cannot end the video's sound early.
def filter_graph(volume, video_sound)
return "[1:a]apad[sound]" unless video_sound
"[0:a]volume=#{volume / 100.0}[own];" \
"[1:a]apad[added];" \
"[own][added]amix=inputs=2:duration=first:normalize=0[sound]"
end
options = parse_options(ARGV)
input = ARGV.shift
output = ARGV.shift || default_output(input)
audio = options[:audio]
[input, audio].each { |path| abort "#{path}: no such file" unless File.exist?(path) }
abort "#{output} already exists; delete it or name another output file" if File.exist?(output)
video_length, video_sound = probe_media(input)
audio_length, has_sound = probe_media(audio)
abort "#{audio} has no sound in it" unless has_sound
if audio_length > video_length
abort "#{audio} is #{audio_length.round(1)}s, longer than the #{video_length.round(1)}s video"
end
puts "#{audio} (#{audio_length.round(1)}s) into #{input} (#{video_length.round(1)}s)" \
"#{", its own sound at #{options[:volume]}%" if video_sound} -> #{output}"
exit 1 unless system("ffmpeg", "-i", input, "-i", audio,
"-filter_complex", filter_graph(options[:volume], video_sound),
"-map", "0:v", "-map", "[sound]", "-shortest", *ENCODE, output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment