Skip to content

Instantly share code, notes, and snippets.

@deseven
Last active January 12, 2025 13:26
Show Gist options
  • Save deseven/96f9ca820c04afcfafe49050f017fc41 to your computer and use it in GitHub Desktop.
Save deseven/96f9ca820c04afcfafe49050f017fc41 to your computer and use it in GitHub Desktop.
Simple script to convert all audio files in current directory to mp3
#!/bin/bash
BLUE='\033[1;34m'
NC='\033[0m'
RED='\033[1;31m'
GREEN='\033[1;32m'
total_files=0
current_file=0
ext="flac"
print_status() {
echo -e "$1"
}
validate_ffmpeg() {
if ! command -v ffmpeg &> /dev/null; then
print_status "${RED}Error: ffmpeg is not installed. Please install ffmpeg before running this script.${NC}"
exit 1
fi
}
get_extension() {
read -p "Please enter the extension to convert from [flac]: " ext
ext=${ext:-flac}
}
count_files() {
for file in *."$ext"; do
if [ -e "$file" ]; then
total_files=$((total_files+1))
print_status "${BLUE}$file${NC}"
fi
done
if [ "$total_files" -eq 0 ]; then
print_status "No files found with extension ${BLUE}$ext${NC} in the current directory. Exiting..."
exit 1
fi
}
confirm_conversion() {
read -p "Found $total_files files to convert. Proceed? (y/n): " -n 1 confirm
echo
if [[ "$confirm" != "y" ]]; then
print_status "Conversion cancelled by user."
exit 0
fi
}
convert_files() {
for file in *."$ext"; do
if [ -e "$file" ]; then
current_file=$((current_file+1))
print_status "${BLUE}Converting file ($current_file/$total_files)...${NC}"
output_file="${file%.$ext}.mp3"
ffmpeg -i "$file" -ab 320k -map_metadata 0 -id3v2_version 3 "$output_file" 2>/dev/null || {
print_status "${RED}Error converting file: $file${NC}"
print_status "Command used: ${BLUE}ffmpeg -i \"$file\" -ab 320k -map_metadata 0 -id3v2_version 3 \"$output_file\"${NC}"
exit 2
}
print_status "${GREEN}Successfully converted: $file${NC}"
fi
done
}
delete_originals() {
read -p "All done! Delete original files? (y/n): " -n 1 delete
echo
if [[ "$delete" == "y" ]]; then
rm -f *."$ext"
print_status "${GREEN}Original files deleted.${NC}"
else
print_status "${BLUE}Original files retained.${NC}"
fi
}
main() {
validate_ffmpeg
get_extension
count_files
confirm_conversion
convert_files
delete_originals
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment