Skip to content

Instantly share code, notes, and snippets.

@mkasberg
Forked from kylophone/loudness.rb
Last active April 29, 2022 07:09
Show Gist options
  • Save mkasberg/0183c2df474bbbb2d75cac94ea0a20a2 to your computer and use it in GitHub Desktop.
Save mkasberg/0183c2df474bbbb2d75cac94ea0a20a2 to your computer and use it in GitHub Desktop.
FFmpeg loudnorm filter - dual pass loudness normalization example - http://k.ylo.ph/2016/04/04/loudnorm.html
#!/usr/bin/env python
import json
import os
from subprocess import check_call, check_output, STDOUT
import sys
if len(sys.argv) != 3:
print "Usage: %s input.wav output.wav" % __file__
sys.exit(1)
infile = sys.argv[1]
outfile = sys.argv[2]
TARGET_I = "-16"
TARGET_TP = "-1.5"
TARGET_LRA = "11"
SAMPLE_RATE = "44100"
BITRATE = "128k"
ffArgs = [
"ffmpeg",
"-hide_banner",
"-i",
infile,
"-af",
"loudnorm=I=%s:TP=%s:LRA=%s:print_format=json" % (TARGET_I, TARGET_TP, TARGET_LRA),
"-f",
"null",
"-"
]
output = check_output(ffArgs, stderr=STDOUT)
outputJson = ''.join(output.splitlines()[-12:])
measured = json.loads(outputJson)
loudnormString = (
"loudnorm=I=%s:TP=%s:LRA=%s:measured_I=%s:measured_TP=%s:measured_LRA=%s:measured_thresh=%s:offset=%s:linear=true:print_format=summary" %
(TARGET_I, TARGET_TP, TARGET_LRA, measured['input_i'], measured['input_tp'], measured['input_lra'], measured['input_thresh'], measured['target_offset'])
)
ffArgs = [
"ffmpeg",
"-y",
"-hide_banner",
"-i",
infile,
"-af",
loudnormString,
"-ar",
SAMPLE_RATE,
"-b:a",
BITRATE,
"-write_xing",
"0",
outfile
]
check_call(ffArgs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment