diff --git a/reduce_bitrate.sh b/reduce_bitrate.sh new file mode 100755 index 0000000..4b4aab9 --- /dev/null +++ b/reduce_bitrate.sh @@ -0,0 +1,81 @@ +#!/bin/bash + +# Define the target bitrate +TARGET_BITRATE="192k" + +echo -e "\n\033[1;32mStarting Bitrate Reduction Script...\033[0m" +echo -e "\033[1;34mTarget Bitrate: \033[0m${TARGET_BITRATE}" + +# Function to process MP3 files safely +process_directory() { + local DIR="$1" + echo "Scanning Directory: $DIR" + + # Use find with -print0 + read -d '' → null-separated = safe with any filename + while IFS= read -r -d '' file; do + echo "Processing: $file" + + # Get current bitrate + METADATA=$(ffprobe -v error -select_streams a:0 -show_entries stream=bit_rate \ + -of default=noprint_wrappers=1:nokey=1 "$file" < /dev/null 2>/dev/null) + + if ! [[ "$METADATA" =~ ^[0-9]+$ ]]; then + METADATA=$(ffprobe -v error -show_entries format=bit_rate \ + -of default=noprint_wrappers=1:nokey=1 "$file" < /dev/null 2>/dev/null) + fi + + if ! [[ "$METADATA" =~ ^[0-9]+$ ]]; then + echo -e "\033[1;31mError:\033[0m Could not read bit rate for $file. Skipping." + continue + fi + + CURRENT_BITRATE=$((METADATA / 1024)) + echo -e "\033[1;32mCurrent Bitrate:\033[0m ${CURRENT_BITRATE} kbps" + + if [ "$CURRENT_BITRATE" -le "${TARGET_BITRATE%k}" ]; then + echo -e "\033[1;33mInfo:\033[0m Already at or below target. Skipping." + continue + fi + + # Create backup + BACKUP_FILE="${file%.mp3}.bak" + if [ ! -f "$BACKUP_FILE" ]; then + cp "$file" "$BACKUP_FILE" + echo -e "\033[1;32mBackup created:\033[0m $BACKUP_FILE" + fi + + # Convert safely using a temporary file with full path + TEMP_FILE="${file%.mp3}_temp_$$.mp3" + + if ffmpeg -nostdin -y -i "$file" -b:a "${TARGET_BITRATE}" -id3v2_version 3 "$TEMP_FILE" > /dev/null 2>&1; then + mv "$TEMP_FILE" "$file" + echo -e "\033[1;32mProcessed \033[0m$file \033[1;32mto ${TARGET_BITRATE} ✅\033[0m" + else + echo -e "\033[1;31mError:\033[0m ffmpeg failed for $file" + rm -f "$TEMP_FILE" + fi + + done < <(find "$DIR" -maxdepth 1 -type f -name "*.mp3" -print0) +} + +# ==================== MAIN ==================== + +# Calculate total size before +TOTAL_SIZE_BEFORE=$(find . -name "*.mp3" -print0 | xargs -0 stat -c '%s' 2>/dev/null | \ + awk '{sum += $1} END {printf "%.2f MB\n", sum/1024/1024}') +echo -e "\n\033[1;32mTotal MP3 size before:\033[0m ${TOTAL_SIZE_BEFORE:-0.00 MB}" + +# Process every directory (including .) +while IFS= read -r -d '' dir; do + process_directory "$dir" +done < <(find . -type d -print0) + +# Calculate total size after +TOTAL_SIZE_AFTER=$(find . -name "*.mp3" -print0 | xargs -0 stat -c '%s' 2>/dev/null | \ + awk '{sum += $1} END {printf "%.2f MB\n", sum/1024/1024}') + +echo -e "\n\033[1;32mTotal MP3 size after:\033[0m ${TOTAL_SIZE_AFTER:-0.00 MB}" +echo -e "\n\033[1;32mBitrate Reduction Script Complete! 🎉\033[0m" + +# Optional: remove all .bak files at the end +# find . -name "*.bak" -type f -delete