Skip to content

Instantly share code, notes, and snippets.

@jlmalone
Created April 3, 2025 03:00
Show Gist options
  • Save jlmalone/ecaf53095537d6d1a303e8b61fa2d72e to your computer and use it in GitHub Desktop.
Save jlmalone/ecaf53095537d6d1a303e8b61fa2d72e to your computer and use it in GitHub Desktop.
mp3 from flac script TODO cleanup
#!/bin/bash
# Improved FLAC-to-MP3 conversion script
# Use a safe IFS for filenames with spaces.
IFS=$(printf '\n\t')
BASE_DIR="$HOME/sietch"
# Use find with -print0 to correctly handle file names with spaces/special characters.
find "$BASE_DIR" -type f -iname "*.flac" -print0 | while IFS= read -r -d '' file; do
echo "Processing: \"$file\""
# Extract metadata (artist and title) using ffprobe.
artist=$(ffprobe -v error -show_entries format_tags=artist \
-of default=noprint_wrappers=1:nokey=1 "$file")
title=$(ffprobe -v error -show_entries format_tags=title \
-of default=noprint_wrappers=1:nokey=1 "$file")
# If artist metadata is missing, use the first directory name under BASE_DIR.
if [[ -z "$artist" ]]; then
# Remove the base directory from the path.
relpath="${file#$BASE_DIR/}"
# Get the first component as the fallback artist.
artist="${relpath%%/*}"
echo " [Info] Artist metadata missing. Falling back to directory name: '$artist'"
fi
# If title metadata is missing, use the filename (without extension) as the fallback title.
if [[ -z "$title" ]]; then
title=$(basename "$file" .flac)
echo " [Info] Title metadata missing. Falling back to filename: '$title'"
fi
# Remove any occurrence of "Topic" (with optional leading/trailing spaces) from the artist name.
artist=$(echo "$artist" | sed -E 's/[[:space:]]*Topic[[:space:]]*//g')
# Trim leading/trailing whitespace from artist and title.
artist=$(echo "$artist" | sed 's/^ *//;s/ *$//')
title=$(echo "$title" | sed 's/^ *//;s/ *$//')
# Construct the output file path. The MP3 will be saved directly in BASE_DIR.
out_file="$BASE_DIR/${artist} - ${title}.mp3"
# If the output file already exists, skip conversion.
if [[ -f "$out_file" ]]; then
echo " Output file already exists: \"$out_file\""
continue
fi
echo " Converting to: \"$out_file\""
# Convert FLAC to MP3 with best quality settings.
ffmpeg -i "$file" -qscale:a 0 -map_metadata 0 -id3v2_version 3 "$out_file"
if [[ $? -eq 0 ]]; then
echo " Converted and saved as: \"$out_file\""
# Optionally, remove the original FLAC file if desired:
# rm "$file"
else
echo " Conversion failed for: \"$file\""
fi
echo ""
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment