Skip to content

Instantly share code, notes, and snippets.

@azazar
Last active January 20, 2023 19:13
Show Gist options
  • Save azazar/f0d96a735eb79f9ae85f8f00caba6c8c to your computer and use it in GitHub Desktop.
Save azazar/f0d96a735eb79f9ae85f8f00caba6c8c to your computer and use it in GitHub Desktop.
A script that encodes mp3 audiobook directory into a single audio file with lowest but usable quality using either mp3, opus or speex codec
#!/bin/bash
set -ex
# fail function to exit with error message
fail() {
echo "$@" 1>&2
exit 1
}
# check that input directory and output file are specified
test -d "$1" || fail "No valid input directory specified"
test -n "$2" || fail "No valid output file specified"
# set input directory and output file variables
inf="$1"
outf="$2"
# create temporary file list
tmpf=$(mktemp)
# find all MP3 files in input directory and add them to temporary file list
find "$inf" -type f -regex '.*\.mp3$' | sort | xargs -I{} echo file \'$(pwd)/{}\' > "$tmpf"
# check if temporary file list is empty
if [ -s "$tmpf" ]; then
# check output file extension
ext="${outf##*.}"
case "$ext" in
mp3)
# re-encode MP3 files and combine them into single file using ffmpeg
outopt="-ac 1 -ar 8000 -c:a libmp3lame -b:a 8k -q:a 1"
;;
opus)
# re-encode MP3 files and combine them into single file using ffmpeg, converting to opus format
outopt="-ac 1 -ar 8000 -c:a libopus -b:a 8k"
;;
spx)
# re-encode MP3 files and combine them into single file using ffmpeg, converting to speex format
outopt="-ac 1 -ar 8000 -c:a libspeex -q:a 1"
;;
*)
fail "Unsupported output file extension"
;;
esac
ffmpeg -f concat -safe 0 -i "$tmpf" $outopt "$outf"
else
fail "No MP3 files found in input directory"
fi
# remove temporary file list
rm "$tmpf"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment