Skip to content

Instantly share code, notes, and snippets.

@olegantonyan
Created May 25, 2016 06:58
Show Gist options
  • Save olegantonyan/3ec65380451d39d71b6caecf8568c32b to your computer and use it in GitHub Desktop.
Save olegantonyan/3ec65380451d39d71b6caecf8568c32b to your computer and use it in GitHub Desktop.
Normalize audio volume using ffmpeg and ruby
def normalize_volume(file)
output = `ffmpeg -i '#{file}' -af "volumedetect" -f null /dev/null 2>&1`
raise "Error getting audio volume from #{file} (#{$?})" unless $?.success?
max_volume = output.scan(/max_volume: ([\-\d\.]+) dB/).flatten.first
mean_volume = output.scan(/mean_volume: ([\-\d\.]+) dB/).flatten.first
return if !max_volume || !mean_volume
max_volume = max_volume.to_f
mean_volume = mean_volume.to_f
target_volume = -14.0
adjustment = target_volume - mean_volume
output_file = "/tmp/#{File.basename(file)}"
result = system(*['ffmpeg', '-i', file, '-af', "volume=#{adjustment}dB", '-c:v', 'copy', output_file])
raise "Error normalizing audio volume of #{file}" unless result
File.rename(output_file, file)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment