Skip to content

Instantly share code, notes, and snippets.

@tvararu
Last active March 16, 2023 11:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvararu/566988b33401b892b87dc0ca963b03b0 to your computer and use it in GitHub Desktop.
Save tvararu/566988b33401b892b87dc0ca963b03b0 to your computer and use it in GitHub Desktop.
#!/bin/bash -eu
if [ "$#" -ne 3 ]; then
echo "Usage: ./flac2mp3.sh <source_dir> <destination_dir> <bitrate>"
exit 1
fi
SRC_DIR="$1"
DEST_DIR="$2"
BITRATE="$3"
if ! command -v ffmpeg >/dev/null 2>&1; then
echo "ffmpeg is not installed. Please install it and try again."
exit 1
fi
if ! command -v parallel >/dev/null 2>&1; then
echo "GNU parallel is not installed. Please install it and try again."
exit 1
fi
export SRC_DIR DEST_DIR BITRATE
convert_flac_to_mp3() {
src_path="$1"
rel_path=$(realpath --relative-to="$SRC_DIR" "$src_path")
dest_path="$DEST_DIR/${rel_path%.flac}.mp3"
if [ ! -f "$dest_path" ]; then
mkdir -p "$(dirname "$dest_path")"
ffmpeg -i "$src_path" -b:a "${BITRATE}k" "$dest_path" 2>/dev/null
echo "Converted: $src_path -> $dest_path"
else
echo "Skipping (already converted): $src_path"
fi
}
export -f convert_flac_to_mp3
copy_non_flac_files() {
src_path="$1"
rel_path=$(realpath --relative-to="$SRC_DIR" "$src_path")
dest_path="$DEST_DIR/${rel_path%.flac}.mp3"
if [ ! -f "$dest_path" ]; then
mkdir -p "$(dirname "$dest_path")"
cp "$src_path" "$dest_path"
echo "Copied: $src_path -> $dest_path"
else
echo "Skipping (already copied): $src_path"
fi
}
export -f copy_non_flac_files
total_files=$(find "$SRC_DIR" -type f -iname '*.flac' | wc -l)
echo "Total Flac files to process: $total_files"
find "$SRC_DIR" -type f -iname '*.flac' -print0 | \
parallel --progress -0 convert_flac_to_mp3
total_files=$(find "$SRC_DIR" -type f -not -iname '*.flac' | wc -l)
echo "Total non-Flac files to process: $total_files"
find "$SRC_DIR" -type f -not -iname '*.flac' -print0 | \
parallel --progress -0 copy_non_flac_files
echo "Conversion completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment