Skip to content

Instantly share code, notes, and snippets.

@lexuzieel
Created January 31, 2021 07:48
Show Gist options
  • Select an option

  • Save lexuzieel/ae99763793461204f50f785b26ade76f to your computer and use it in GitHub Desktop.

Select an option

Save lexuzieel/ae99763793461204f50f785b26ade76f to your computer and use it in GitHub Desktop.
#!/bin/bash
# REQUIREMENTS TO RUN THIS SCRIPT:
# - ffmpeg
# - python
# HOW TO RUN:
# - `cd` into the directory with `source.mp4`
# - Run this script
# OUTPUT:
# - source.normalized.mp4 - file with normalized audio level
# - source.normalized.equalized.mp4 - file with normalized audio level & compensated volume to match the original
# Normalize source audio using ffmpeg-normalize tool (https://github.com/slhck/ffmpeg-normalize)
# Source: https://superuser.com/a/323127/404976
# Step 1: Install python package globally
pip3 install ffmpeg-normalize
if [ $? -ne 0 ]; then
exit
fi
SOURCE=source.mp4
NAME="$(echo $SOURCE | sed 's/\.[^\.]*$//')"
# Step 2: Normalize audio using EBU R128 (https://en.wikipedia.org/wiki/EBU_R_128).
ffmpeg-normalize $SOURCE -o $NAME.normalized.mp4 -c:a aac -b:a 192k
# Step 3: Compensate gain difference between source and normalized audio.
ORIGINAL_MAX_VOLUME=$(
ffmpeg -i $SOURCE -af "volumedetect" -vn -sn -dn -f null /dev/null 2>&1 | grep max_volume | cut -d : -f 2 | sed 's/^ *//' | cut -d ' ' -f 1
)
NORMALIZED_MAX_VOLUME=$(
ffmpeg -i $NAME.normalized.mp4 -af "volumedetect" -vn -sn -dn -f null /dev/null 2>&1 | grep max_volume | cut -d : -f 2 | sed 's/^ *//' | cut -d ' ' -f 1
)
GAIN=$(python -c "print($NORMALIZED_MAX_VOLUME - $ORIGINAL_MAX_VOLUME)")
yes N | ffmpeg -i $NAME.normalized.mp4 -af "volume=${GAIN}dB" -c:v copy -c:a aac -b:a 192k $NAME.normalized.equalized.mp4
# Step 4: Trim both source and resulting video for the demo
# ffmpeg -hide_banner -y -i $SOURCE -copyinkf -ss 00:06:41 -t 19 $NAME.trimmed-01.original.mp4
# ffmpeg -hide_banner -y -i $NAME.normalized.equalized.mp4 -copyinkf -ss 00:06:41 -t 19 $NAME.trimmed-01.normalized.equalized.mp4
# ffmpeg -hide_banner -y -i $SOURCE -copyinkf -ss 00:06:49 -t 5 $NAME.trimmed-02.original.mp4
# ffmpeg -hide_banner -y -i $NAME.normalized.equalized.mp4 -copyinkf -ss 00:06:49 -t 5 $NAME.trimmed-02.normalized.equalized.mp4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment