Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split flac and encode it to mp3/ogg
#!/bin/bash -x
# Requered tools: cuetools, shntool, id3v2, vorbis-tools, lame
#
LAMEOPTS="-b 320 --quiet"
OGGOPTS="-b 320 --quiet"
usage () {
echo Usage: "$(basename $0)" "-f /path/to.flac -s /path/to.cue -e mp3|ogg"
echo "mp3 format is used by default"
}
while getopts ":s:f:e:" opt; do
case $opt in
f)
FILE="$OPTARG"
;;
s)
SPLIT="$OPTARG"
;;
e)
FMT="$OPTARG"
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
*)
usage
exit 1
;;
esac
done
# Set default format to mp3
case ${FMT:="mp3"} in
mp3|MP3|ogg|OGG)
;;
*)
echo "Unknown format $FMT" >&2
exit 1
;;
esac
# Check both files
if [ ! -f "$FILE" -o ! -f "$SPLIT" ]
then
usage >&2
exit 1
fi
#Get number of tracks
NUMTRACKS=`cueprint -d '%N' "${SPLIT}"`
for i in `seq 1 $NUMTRACKS`
do
# Clear previous obtained variables
unset PERFORMER
unset ALBUM
unset TITLE
# Set performer, album, track title
PERFORMER=$(cueprint -n $i -t '%p' "${SPLIT}")
PERFORMER=${PERFORMER:-$(cueprint -d '%P' ./*.cue)}
ALBUM=$(cueprint -d '%T' "${SPLIT}")
TITLE=$(cueprint -n $i -t '%t' "${SPLIT}")
## Check perfomer, album and track title
if [ -z "$PERFORMER" ]
then
echo "Track $i: Can not obtain performer from cue, set it to 'Unknown Artist'" >&2
PERFORMER="Unknown Artist"
fi
if [ -z "$ALBUM" ]
then
echo "Track $i: Can not obtain album from cue, set it to 'Unknown Album'" >&2
ALBUM="Unknown Album"
fi
if [ -z "$TITLE" ]
then
echo "Track $i: Can not obtain track from cue, set it to 'Track $i'" >&2
TITLE="Track $i"
fi
## End
# Split and encoding files
echo "Encoding track $i/$NUMTRACKS."
if [ "$FMT" = "mp3" -o "$FMT" = "MP3" ]
then
cuebreakpoints "$SPLIT"| shnsplit -q -o "cust ext=mp3 lame $LAMEOPTS - %f" \
-x $i -O always -a "" -z " - $TITLE" "$FILE"
OUTPUT=`printf "%.2d - ${TITLE}.mp3" $i`
id3v2 -T $i -a "$PERFORMER" -A "$ALBUM" -t "$TITLE" "$OUTPUT"
fi
if [ "$FMT" = "ogg" -o "$FMT" = "OGG" ]
then
cuebreakpoints "$SPLIT"|shnsplit -q -o "cust ext=ogg oggenc $OGGOPTS -o %f -" \
-x $i -O always -a "" -z " - $TITLE" "$FILE"
OUTPUT=`printf "%.2d - ${TITLE}.ogg" $i`
echo -e "TRACKNUMBER=${i}\nARTIST=${PERFORMER}\nPERFORMER=${PERFORMER}" \
"\nALBUM=${ALBUM}\nTITLE=${TITLE}\n"|vorbiscomment "$OUTPUT"
fi
done
@KoolKeith
Copy link

KoolKeith commented Jan 9, 2020

Thank you very much. Works perfectly. Just what I needed !

@lid3rs
Copy link

lid3rs commented Mar 6, 2020

Converting to mp3 not working. "Cannot split to mp3" error. OGG works perectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment