Skip to content

Instantly share code, notes, and snippets.

@shirish87
Forked from vi/split_by_silence.sh
Last active December 15, 2022 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shirish87/8c964f1f0fb33a6f8835c21048468aba to your computer and use it in GitHub Desktop.
Save shirish87/8c964f1f0fb33a6f8835c21048468aba to your computer and use it in GitHub Desktop.
Using FFmpeg to split mp3 audiobook file into mp3 parts based on audio volume level
#!/bin/bash
IN="$1"
MIN_DUR_MINS="${2:-30}"
MIN_PART_DURATION_SECS=$(($MIN_DUR_MINS * 60))
IN_PATH=`realpath "$1"`
DEFAULT_OUTDIR="$(dirname "$IN_PATH")/parts"
OUTDIR="${3:-$DEFAULT_OUTDIR}"
OUTFILE_PATTERN="${OUTDIR}/part-%03d.mp3"
true ${SD_PARAMS:="-55dB:d=0.3"};
export MIN_PART_DURATION_SECS
echo "Determining split points..." >& 2
SPLITS=$(
ffmpeg -v warning -i "$IN" -af silencedetect="$SD_PARAMS",ametadata=mode=print:file=-:key=lavfi.silence_start -vn -sn -f s16le -y /dev/null \
| grep lavfi.silence_start= \
| cut -f 2-2 -d= \
| perl -ne '
our $prev;
INIT { $prev = 0.0; }
chomp;
if (($_ - $prev) >= $ENV{MIN_PART_DURATION_SECS}) {
print "$_,";
$prev = $_;
}
' \
| sed 's!,$!!'
)
echo "Splitting points are $SPLITS"
mkdir -p "$OUTDIR"
echo "Saving ${MIN_DUR_MINS} min parts to ${OUTDIR}"
ffmpeg -v warning -i "$IN" -c copy -map 0 -f segment -segment_times "$SPLITS" "$OUTFILE_PATTERN"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment