Skip to content

Instantly share code, notes, and snippets.

@dtcooper
Last active January 31, 2018 20:58
Show Gist options
  • Save dtcooper/3f9dc7fac423134b214c4d34ee5fda3c to your computer and use it in GitHub Desktop.
Save dtcooper/3f9dc7fac423134b214c4d34ee5fda3c to your computer and use it in GitHub Desktop.
#!/bin/sh
if [ -z "$1" ]; then
echo "Usage: $(basename "$0") input.wav [input.wav] [...]"
exit 0
fi
red () {
echo "\x1B[91m$1\x1B[0m"
}
blue () {
echo "\x1B[96m$1\x1B[0m"
}
strip_extension () {
echo "$1" | rev | cut -f 2- -d '.' | rev
}
filesize () {
FSIZE="$(wc -c "$1" | awk '{print $1}')"
REDUCTION=
if [ "$2" ]; then
REDUCTION=", $(echo "scale=2;(1 - ${FSIZE}/$2) * 100" | bc)% reduction"
fi
KB=1024
MB=1048576
GB=1073741824
TB=1099511627776
PB=1125899906842624
[ "$FSIZE" -lt $KB ] 2>/dev/null && echo "$FSIZE bytes$REDUCTION" && return
[ "$FSIZE" -lt $MB ] 2>/dev/null && echo "$FSIZE bytes [$(echo "scale=2;$FSIZE/$KB" | bc)KiB]$REDUCTION" && return
[ "$FSIZE" -lt $GB ] 2>/dev/null && echo "$FSIZE bytes [$(echo "scale=2;$FSIZE/$MB" | bc)MiB]$REDUCTION" && return
[ "$FSIZE" -lt $TB ] 2>/dev/null && echo "$FSIZE bytes [$(echo "scale=2;$FSIZE/$GB" | bc)GiB]$REDUCTION" && return
[ "$FSIZE" -lt $PB ] 2>/dev/null && echo "$FSIZE bytes [$(echo "scale=2;$FSIZE/$TB" | bc)TiB]$REDUCTION" && return
}
current_wave_file=
current_flac_file=
clean_up_and_exit () {
echo
if [ -e "$current_wave_file" -a -e "$current_flac_file" ]; then
red "Cleaning up partially encoded \"$current_flac_file\""
rm "$current_flac_file"
fi
exit
}
trap clean_up_and_exit SIGINT
for current_wave_file in "$@"; do
if [ ! -e "$current_wave_file" ]; then
red "\"$current_wave_file\" does not exist"
elif [ "$(file --mime-type --brief "$current_wave_file")" = "audio/x-wav" ]; then
PREVIOUS_SIZE="$(wc -c "$current_wave_file" | awk '{print $1}')"
blue "Encoding \"$current_wave_file\"... (Before: $(filesize "$current_wave_file"))"
current_flac_file="$(strip_extension "$current_wave_file").flac"
flac \
--delete-input-file \
--keep-foreign-metadata \
--verify \
"$current_wave_file"
if [ "$?" = 0 ]; then
blue "Done! (After: $(filesize "$current_flac_file" $PREVIOUS_SIZE))"
else
red 'flac exited with and error!'
fi
else
red "\"$current_wave_file\" not a wave file"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment