Skip to content

Instantly share code, notes, and snippets.

@ldotlopez
Last active December 15, 2015 06:59
Show Gist options
  • Save ldotlopez/5220061 to your computer and use it in GitHub Desktop.
Save ldotlopez/5220061 to your computer and use it in GitHub Desktop.
Q&D flac2mp3 to be used with cron.
#!/bin/bash
# Configurables
LOC="${LOC:-$1}" # You can set LOC via env variable or argument
FLAC_BIN="${FLAC_BIN:-flac}"
METAFLAC_BIN="${METAFLAC_BIN:-metaflac}"
LAME_BIN="${LAME_BIN:-lame}"
ID3_BIN="${ID3_BIN:-id3tag}"
V="${V:-true}" # set to echo to enable debug
W="${W:-true}" # set to echo to enable warnings
# End configurables
if [ -z "$LOC" -o ! -d "$LOC" ]; then
echo "Invalid LOC" >&2
exit 1
fi
# Check for utilities
T=0
for BIN in $FLAC_BIN $METAFLAC_BIN $LAME_BIN $ID3_BIN
do
if [ -z "$(which "$BIN")" ]; then
echo "Missing $BIN" >&2
T=1
fi
done
if [ $T != 0 ]; then
exit 1
fi
IFS="
"
for a in $(find "$LOC" -type f -a -iname '*.flac')
do
OUTF=${a%.$FLAC_BIN}.mp3
# Convert only if output file doesn't exists or if it's older than flac
# file
if [ -e "$OUTF" -a "$OUTF" -nt "$a" ]; then
$W "Skipping '$a' conversion, output file exists" >&2
continue
fi
# Extract metadata
ARTIST=`$METAFLAC_BIN "$a" --show-tag=ARTIST | sed s/.*=//g`
TITLE=`$METAFLAC_BIN "$a" --show-tag=TITLE | sed s/.*=//g`
ALBUM=`$METAFLAC_BIN "$a" --show-tag=ALBUM | sed s/.*=//g`
TRACKNUMBER=`$METAFLAC_BIN "$a" --show-tag=TRACKNUMBER | sed s/.*=//g`
DATE=`$METAFLAC_BIN "$a" --show-tag=DATE | sed s/.*=//g`
#GENRE=`$METAFLAC_BIN "$a" --show-tag=GENRE | sed s/.*=//g`
$V -ne "$(basename -- "$a"): "
# Convert file
$V -n "converting"
$FLAC_BIN -s -c -d "$a" | $LAME_BIN --silent -m j -q 0 --vbr-new -V 0 -s 44.1 - "${OUTF}.tmp"
if [ $? -ne 0 ]; then
rm -- "${OUTF}.tmp"
$V -n ": failed"
continue
else
$V -n ": ok"
fi
# Sync tags
$V -n ", tags"
$ID3_BIN --v2tag --song="$TITLE" --track="${TRACKNUMBER:-0}" --artist="$ARTIST" --album="$ALBUM" --year="$DATE" "${OUTF}.tmp" 1>/dev/null
if [ $? -ne 0 ]; then
rm -- "${OUTF}.tmp"
$V -n ": failed"
continue
else
$V -n ": ok"
fi
# Move file to final location
mv "${OUTF}.tmp" "${OUTF}"
$V
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment