Skip to content

Instantly share code, notes, and snippets.

@rileyjshaw
Created April 19, 2024 15:45
Show Gist options
  • Save rileyjshaw/1fd66b82ca92452b2be30175f1d9c87e to your computer and use it in GitHub Desktop.
Save rileyjshaw/1fd66b82ca92452b2be30175f1d9c87e to your computer and use it in GitHub Desktop.
Traverse subdirectories (albums) and convert them to a flat list of 192kbps mp3s. Used for the Digital Media Sound Player.
#!/bin/bash
# Ensure the 'converted' directory exists
mkdir -p converted
# Initialize a counter for file naming
counter=1
# Allowed audio file extensions
allowed_extensions="flac mp3 wav"
# Function to convert files
convert_files() {
local path="$1"
for file in "$path"/*; do
if [[ -f "$file" ]]; then
# Extract the file extension
local extension="${file##*.}"
local filename="${file##*/}" # Extracts only the filename from the path
# Check if the file extension is one of the allowed types
if [[ $allowed_extensions =~ $extension ]]; then
local bitrate="192k"
# Get current file's bitrate
current_bitrate=$(ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate -of default=noprint_wrappers=1:nokey=1 "$file")
# Check if bitrate conversion is necessary
if [[ "$current_bitrate" != "N/A" && "$current_bitrate" -lt 192000 ]]; then
bitrate="${current_bitrate}k"
fi
# Convert the file, ensuring all metadata including album art is removed
ffmpeg -i "$file" -ab $bitrate -map_metadata -1 -map 0:a -vn -y "./converted/$(printf "%03d" $counter)_${filename%.${extension}}.mp3"
((counter++))
fi
elif [[ -d "$file" && "${file##*/}" != "converted" ]]; then
# Recursive call if directory and not the 'converted' directory
convert_files "$file"
fi
done
}
# Start conversion from the current directory
convert_files "."
echo "Conversion complete. Files are saved in 'converted' directory."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment