Skip to content

Instantly share code, notes, and snippets.

@mia-riezebos
Last active January 6, 2022 20:41
Show Gist options
  • Save mia-riezebos/0d2e660146b359641336ff22c0b63841 to your computer and use it in GitHub Desktop.
Save mia-riezebos/0d2e660146b359641336ff22c0b63841 to your computer and use it in GitHub Desktop.
Recursive converter using ffmpeg (example uses flac -> m4a/alac)
#!/bin/bash
# assembled & improved by mia-cx
# sources used:
# - https://superuser.com/a/1307579
# - https://stackoverflow.com/a/31605674
# - https://stackoverflow.com/a/965072
# read relative "working" directory
read -e -p "Working directory: " -i "./" RELDIR
# set working directory
PWD="$(
cd "$(dirname "$DIR")"
pwd
)"
# echo $PWD
# what files should be processed
read -e -p "Input pattern: " -i ".flac" PATTERN
# what is the output format
read -e -p "Output extension: " -i ".m4a" EXTENSION
read -e -p "Output codec: " -i "alac" CODEC
# marker will be appended to files that have been processed,
# so that the script won't process them more than once
MARKER="formats"
echo -n "Finding candidate files .."
FILELIST=$(find "$PWD" -type f -name "*$PATTERN")
echo ".. "$(echo -e "$FILELIST" | wc -l)" found"
# echo "$FILELIST"
while read FILEPATH; do
# A bit of healthy paranoia
test -z "$FILEPATH" && continue
test -f "$FILEPATH" || continue
echo "Working on $FILEPATH .."
# New file name
FILENAME=$(basename -- "$FILEPATH")
INPUTEXTENSION="${FILENAME##*.}"
FILENAME="${FILENAME%.*}"
# echo $FILENAME
# echo $INPUTEXTENSION
# echo $EXTENSION
BP=$(dirname "$FILEPATH")
NBP=${BP#$PWD/}
NEWFILEPATH="$PWD/$MARKER/$EXTENSION/$NBP/$FILENAME$EXTENSION"
# echo $NEWFILEPATH
# Skip result files
ISRESULT=$(echo "$FILEPATH" | grep -e "/$MARKER/")
if test -n "$ISRESULT"; then
echo ".. skipping (is a result file)"
continue
fi
# Skip untagged
ISUNTAGGED=$(echo "$FILEPATH" | grep "/untagged/")
if test -n "$ISUNTAGGED"; then
echo ".. skipping (is an untagged file)"
continue
fi
# Skip processed files
if test -f "$NEWFILEPATH"; then
echo ".. skipping (result file exists)"
continue
fi
# create marker directory
mkdir -p "$PWD/$MARKER/$EXTENSION/$NBP"
# Process
echo -n ".. running ffmpeg .."
RES=$(ffmpeg -loglevel info -y -i "$FILEPATH" -c:a $CODEC -c:v copy "$NEWFILEPATH" </dev/null 2>&1)
# echo $RES
echo ".. done (exit code $?)"
done < <(echo -e "$FILELIST")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment