Come riparare i file musicali mp3
Talvolta i file musicali mp3 si possono corrompere e in una collezione vasta potrebbe essere difficile individuarli.
Richiede ffmpeg nel PATH e le utility GNU coreutils/findutils in particolare find con supporto a -printf e awk per i confronti float; per la gestione dell’I/O utilizza la process substitution (< <(…)) per evitare che i cicli while vengano eseguiti in subshell separate, preservando così l’aggiornamento dei contatori di stato in memoria.
Viene prevista anche una funzione che tenta il recupero dei file corrotti eseguendo un ripristino strutturale non distruttivo dei flussi audio MP3 elencati in report_mp3_error.txt, operando in tre fasi distinte per ogni singolo file:
- Parsing e Gestione I/O: Legge il file di report saltando le prime due righe di intestazione tramite tail -n +3 ed estrae il percorso esatto del file utilizzando la parameter expansion ${line#*] }. Il ciclo while utilizza la process substitution (< <(…)) per evitare l’esecuzione in una subshell separata, mantenendo così coerenti in memoria i contatori REPAIRED_COUNT e FAILED_COUNT.
- Stream Copy Tollerante agli Errori: Invoca ffmpeg con il flag -err_detect ignore_err e la direttiva -c copy. Questa combinazione forza il demuxer a scartare i frame audio corrotti o troncati e a rigenerare le intestazioni (header) del contenitore senza effettuare alcuna ricodifica, preservando al 100% la qualità audio originale ed evitando perdita generazionale.
- Validazione Post-Ripristino e Atomicità: L’output viene scritto su un file temporaneo nascosto (.tmp_repair_<filename>) nella medesima directory del file target. Prima di consolidare la modifica, lo script verifica che il file esista, non sia vuoto (-s) e superi il controllo di integrità e soglia dB tramite check_mp3_health. Solo in caso di esito positivo il file originale viene sovrascritto con mv -f (operazione atomica sullo stesso filesystem); in caso contrario, il file temporaneo viene rimosso (rm -f) lasciando intatto l’originale.
Ogni tentativo viene tracciato in report_mp3_repair.txt classificando l’esito in quattro stati: REPAIRED, SKIPPED, NOT REPAIRED, ERROR e chiudendo con un riepilogo statistico finale.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
#!/bin/bash # Default values DEFAULT_DIR="$PWD" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE}")" && pwd)" REPORT_FILENAME="report_mp3_error.txt" REPLACE_REPORT="$SCRIPT_DIR/report_mp3_replace.txt" REPAIR_REPORT="$SCRIPT_DIR/report_mp3_repair.txt" DEFAULT_THRESHOLD="-6.0" # Main Menu Loop (Entry Point) main_menu() { while true; do clear echo "==========================================" echo " MP3 UTILITY MENU " echo "==========================================" echo "1. Find corrupted MP3 files" echo "2. Replace corrupted MP3 files" echo "3. Repair corrupted MP3 files (ffmpeg)" echo "X. Exit program" echo "==========================================" read -r -p "Select an option [1, 2, 3, X]: " CHOICE case "$CHOICE" in 1) find_mp3_corrupted ;; 2) replace_mp3_files ;; 3) repair_mp3_files ;; [Xx]) echo "Exiting program." exit 0 ;; *) echo "" echo "Invalid option '$CHOICE'. Please try again." read -r -p "Press Enter to return to the menu..." ;; esac done } # Function 1: Find corrupted MP3 files find_mp3_corrupted() { echo "" # Interactive prompt with editable default values read -e -r -p "Enter the report directory path: " -i "$DEFAULT_DIR" INPUT_DIR TARGET_DIR="${INPUT_DIR:-$DEFAULT_DIR}" TARGET_DIR="${TARGET_DIR%/}" if [ ! -d "$TARGET_DIR" ]; then echo "Error: Directory '$TARGET_DIR' does not exist." >&2 read -r -p "Press Enter to return to the menu..." return 1 fi REPORT="$TARGET_DIR/$REPORT_FILENAME" read -e -r -p "Enter the threshold in dB: " -i "$DEFAULT_THRESHOLD" INPUT_THRESHOLD THRESHOLD="${INPUT_THRESHOLD:-$DEFAULT_THRESHOLD}" echo "" echo "Report of MP3 files with abnormal volume (> $THRESHOLD dB) - $(date)" > "$REPORT" echo "==========================================================" >> "$REPORT" echo "Starting audio analysis. The report will be saved to: $REPORT" echo "" CURRENT_DIR="" # Find all mp3 files sorted alphabetically by folder find . -type f -iname "*.mp3" | sort | while IFS= read -r file; do NEW_DIR=$(dirname "$file") if [ "$NEW_DIR" != "$CURRENT_DIR" ]; then CURRENT_DIR="$NEW_DIR" echo "--> Checking folder: $CURRENT_DIR" fi status=$(check_mp3_health "$file" "$THRESHOLD") if [ $? -ne 0 ]; then if [ "$status" = "UNREADABLE" ]; then echo " [!] UNREADABLE: $(basename "$file")" echo "[UNREADABLE] $file" >> "$REPORT" else echo " [!] LOUD/CORRUPT ($status dB): $(basename "$file")" echo "[$status dB] $file" >> "$REPORT" fi fi done echo "" echo "Analysis complete! Check the report file at: $REPORT" echo "" read -r -p "Press Enter to return to the menu..." } # Function 2: Replace corrupted MP3 files replace_mp3_files() { echo "" # 1. Ask for the report directory read -e -r -p "Enter the directory containing '$REPORT_FILENAME': " -i "$DEFAULT_DIR" INPUT_REPORT_DIR REPORT_DIR="${INPUT_REPORT_DIR:-$DEFAULT_DIR}" REPORT_DIR="${REPORT_DIR%/}" REPORT="$REPORT_DIR/$REPORT_FILENAME" if [ ! -f "$REPORT" ]; then echo "Error: Report file not found at '$REPORT'. Run option 1 first." >&2 read -r -p "Press Enter to return to the menu..." return 1 fi # 2. Ask for the source directory containing healthy MP3s (e.g. /mp3ok) read -e -r -p "Enter the source directory with healthy MP3 files (e.g. /mp3ok): " SOURCE_DIR SOURCE_DIR="${SOURCE_DIR%/}" if [ -z "$SOURCE_DIR" ] || [ ! -d "$SOURCE_DIR" ]; then echo "Error: Source directory '$SOURCE_DIR' does not exist." >&2 read -r -p "Press Enter to return to the menu..." return 1 fi # 3. Ask for threshold to validate replacement files read -e -r -p "Enter the threshold in dB to verify healthy files: " -i "$DEFAULT_THRESHOLD" INPUT_THRESHOLD THRESHOLD="${INPUT_THRESHOLD:-$DEFAULT_THRESHOLD}" # Count total corrupted files to process for progress indicator TOTAL_FILES=$(tail -n +3 "$REPORT" | grep -c '[^[:space:]]') CURRENT_COUNT=0 REPLACED_COUNT=0 FAILED_COUNT=0 # Initialize replacement report in the script's directory echo "Report of MP3 Replacement Process - $(date)" > "$REPLACE_REPORT" echo "==========================================================" >> "$REPLACE_REPORT" echo "" echo "Starting replacement process ($TOTAL_FILES files to process)..." echo "" # Read corrupted file paths from report (skipping the first 2 header lines) while IFS= read -r line; do [ -z "$line" ] && continue CURRENT_COUNT=$((CURRENT_COUNT + 1)) # Strip the leading "[... dB] " or "[UNREADABLE] " prefix to get the exact file path corrupt_file="${line#*] }" filename=$(basename "$corrupt_file") echo "[$CURRENT_COUNT/$TOTAL_FILES] Processing: $filename" if [ ! -f "$corrupt_file" ]; then echo " [!] Target file '$corrupt_file' no longer exists. Skipping." echo "[SKIPPED - TARGET MISSING] $corrupt_file" >> "$REPLACE_REPORT" echo "----------------------------------------------------------" >> "$REPLACE_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) continue fi # Find all matching files in SOURCE_DIR and subdirectories, sorted by modification time (newest first) found_valid=0 candidates_checked=0 while IFS= read -r candidate; do [ -z "$candidate" ] && continue candidates_checked=$((candidates_checked + 1)) echo " [?] Checking candidate #$candidates_checked: $candidate" status=$(check_mp3_health "$candidate" "$THRESHOLD") if [ $? -eq 0 ]; then echo " [>] Copying healthy file to target..." cp -f "$candidate" "$corrupt_file" if [ $? -eq 0 ]; then echo " [OK] Replaced successfully ($status dB)" echo "[REPLACED]" >> "$REPLACE_REPORT" echo "FROM: $candidate" >> "$REPLACE_REPORT" echo "TO: $corrupt_file" >> "$REPLACE_REPORT" echo "----------------------------------------------------------" >> "$REPLACE_REPORT" REPLACED_COUNT=$((REPLACED_COUNT + 1)) else echo " [!] Error copying '$candidate' to '$corrupt_file'" echo "[ERROR - COPY FAILED]" >> "$REPLACE_REPORT" echo "FROM: $candidate" >> "$REPLACE_REPORT" echo "TO: $corrupt_file" >> "$REPLACE_REPORT" echo "----------------------------------------------------------" >> "$REPLACE_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) fi found_valid=1 break else echo " [!] Candidate is ALSO CORRUPTED/UNREADABLE ($status). Trying next..." fi done < <(find "$SOURCE_DIR" -type f -name "$filename" -printf "%T@ %p\n" 2>/dev/null | sort -rn | cut -d' ' -f2-) if [ "$found_valid" -eq 0 ]; then FAILED_COUNT=$((FAILED_COUNT + 1)) if [ "$candidates_checked" -gt 0 ]; then echo " [X] NOT REPLACED: All $candidates_checked candidate(s) found in '$SOURCE_DIR' were ALSO CORRUPTED." echo "[NOT REPLACED - ALL SOURCE FILES CORRUPTED ($candidates_checked checked)]" >> "$REPLACE_REPORT" echo "TARGET: $corrupt_file" >> "$REPLACE_REPORT" echo "----------------------------------------------------------" >> "$REPLACE_REPORT" else echo " [X] NOT REPLACED: File not found in '$SOURCE_DIR'." echo "[NOT REPLACED - NOT FOUND IN SOURCE]" >> "$REPLACE_REPORT" echo "TARGET: $corrupt_file" >> "$REPLACE_REPORT" echo "----------------------------------------------------------" >> "$REPLACE_REPORT" fi fi done < <(tail -n +3 "$REPORT") # Append summary to the report echo "" >> "$REPLACE_REPORT" echo "SUMMARY: $REPLACED_COUNT replaced, $FAILED_COUNT not replaced (out of $TOTAL_FILES total)." >> "$REPLACE_REPORT" echo "" echo "Replacement process complete! Report saved to: $REPLACE_REPORT" echo "" cat "$REPLACE_REPORT" echo "" read -r -p "Press Enter to return to the menu..." } # Function 3: Repair corrupted MP3 files using ffmpeg repair_mp3_files() { echo "" read -e -r -p "Enter the directory containing '$REPORT_FILENAME': " -i "$DEFAULT_DIR" INPUT_REPORT_DIR REPORT_DIR="${INPUT_REPORT_DIR:-$DEFAULT_DIR}" REPORT_DIR="${REPORT_DIR%/}" REPORT="$REPORT_DIR/$REPORT_FILENAME" if [ ! -f "$REPORT" ]; then echo "Error: Report file not found at '$REPORT'. Run option 1 first." >&2 read -r -p "Press Enter to return to the menu..." return 1 fi read -e -r -p "Enter the threshold in dB to verify repaired files: " -i "$DEFAULT_THRESHOLD" INPUT_THRESHOLD THRESHOLD="${INPUT_THRESHOLD:-$DEFAULT_THRESHOLD}" TOTAL_FILES=$(tail -n +3 "$REPORT" | grep -c '[^[:space:]]') CURRENT_COUNT=0 REPAIRED_COUNT=0 FAILED_COUNT=0 echo "Report of MP3 Repair Process - $(date)" > "$REPAIR_REPORT" echo "==========================================================" >> "$REPAIR_REPORT" echo "" echo "Starting repair process ($TOTAL_FILES files to process)..." echo "" while IFS= read -r line; do [ -z "$line" ] && continue CURRENT_COUNT=$((CURRENT_COUNT + 1)) corrupt_file="${line#*] }" filename=$(basename "$corrupt_file") dir_name=$(dirname "$corrupt_file") temp_file="$dir_name/.tmp_repair_${filename}" echo "[$CURRENT_COUNT/$TOTAL_FILES] Attempting repair: $filename" if [ ! -f "$corrupt_file" ]; then echo " [!] Target file '$corrupt_file' no longer exists. Skipping." echo "[SKIPPED - TARGET MISSING] $corrupt_file" >> "$REPAIR_REPORT" echo "----------------------------------------------------------" >> "$REPAIR_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) continue fi ffmpeg -nostdin -y -err_detect ignore_err -i "$corrupt_file" -c copy "$temp_file" >/dev/null 2>&1 ffmpeg_exit=$? if [ $ffmpeg_exit -eq 0 ] && [ -s "$temp_file" ]; then status=$(check_mp3_health "$temp_file" "$THRESHOLD") if [ $? -eq 0 ]; then mv -f "$temp_file" "$corrupt_file" if [ $? -eq 0 ]; then echo " [OK] Repaired and verified ($status dB)" echo "[REPAIRED - $status dB] $corrupt_file" >> "$REPAIR_REPORT" echo "----------------------------------------------------------" >> "$REPAIR_REPORT" REPAIRED_COUNT=$((REPAIRED_COUNT + 1)) else rm -f "$temp_file" echo " [!] Error replacing original file with repaired version." echo "[ERROR - OVERWRITE FAILED] $corrupt_file" >> "$REPAIR_REPORT" echo "----------------------------------------------------------" >> "$REPAIR_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) fi else rm -f "$temp_file" echo " [X] NOT REPAIRED: File still corrupted or loud after rebuild ($status)." echo "[NOT REPAIRED - STILL CORRUPTED ($status)] $corrupt_file" >> "$REPAIR_REPORT" echo "----------------------------------------------------------" >> "$REPAIR_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) fi else rm -f "$temp_file" echo " [X] NOT REPAIRED: ffmpeg failed to rebuild stream." echo "[NOT REPAIRED - FFMPEG FAILED] $corrupt_file" >> "$REPAIR_REPORT" echo "----------------------------------------------------------" >> "$REPAIR_REPORT" FAILED_COUNT=$((FAILED_COUNT + 1)) fi done < <(tail -n +3 "$REPORT") echo "" >> "$REPAIR_REPORT" echo "SUMMARY: $REPAIRED_COUNT repaired, $FAILED_COUNT not repaired (out of $TOTAL_FILES total)." >> "$REPAIR_REPORT" echo "" echo "Repair process complete! Report saved to: $REPAIR_REPORT" echo "" cat "$REPAIR_REPORT" echo "" read -r -p "Press Enter to return to the menu..." } # Helper function: Check if an MP3 file is healthy (returns 0 if OK, 1 if loud/corrupted or unreadable) check_mp3_health() { local file_path="$1" local threshold="$2" local vol local is_loud vol=$(ffmpeg -nostdin -i "$file_path" -af "volumedetect" -f null /dev/null 2>&1 | grep "mean_volume:" | awk '{print $5}') if [ -n "$vol" ]; then is_loud=$(awk -v v="$vol" -v s="$threshold" 'BEGIN {print (v > s) ? 1 : 0}') if [ "$is_loud" -eq 1 ]; then echo "$vol" return 1 fi echo "$vol" return 0 else echo "UNREADABLE" return 1 fi } # Start the program main_menu |


