Convert MP3 files using FFmpeg

28 || 0  || 2018-04-14 06:04:28 || root || || Bash

Convert MP3 files using FFmpeg. Script makes the following:

  1. Gets all MP3 files in current directory
  2. Shuffles files in random order
  3. Removes "bad" characters from files' names
  4. Converts each MP3 file using the same audio codec (libmp3lame)
  5. Saves each new MP3 file in "results" directory

#!/bin/bash

result_dir="./results"
start_date=`date`

mkdir $result_dir
rm -rf "$result_dir/*"

mp3_files_list=`find . -type f ! -path "${result_dir}*" -name "*.mp3" | sort -R | sort -R | sort -R | sort -R | sort -R`
IFS=$'\n'
mp3_file_number=1
mp3_files_total=0

for mp3_current_file in $mp3_files_list;
do
    mp3_files_total=$((mp3_files_total + 1));
done

for mp3_file in $mp3_files_list;
do
    mp3_file_name=`mp3info -p "${mp3_file_number}_%f" "$mp3_file"`;
    mp3_file_name_new=${mp3_file_name//" "/"_"}
    mp3_file_name_new=${mp3_file_name_new//")"/"_"}
    mp3_file_name_new=${mp3_file_name_new//"("/"_"}
    mp3_file_name_new=${mp3_file_name_new//"'"/"_"}
    mp3_file_name_new=${mp3_file_name_new//'"'/"_"}
    mp3_file_name_new=${mp3_file_name_new//"."/"_"}
    mp3_file_name_new=${mp3_file_name_new//","/"_"}
    mp3_file_name_new=${mp3_file_name_new//"-"/"_"}
    mp3_file_name_new=${mp3_file_name_new//"__"/"_"}
    mp3_file_name_new=${mp3_file_name_new//"&"/"_and_"}
    mp3_file_name_new="${mp3_file_name_new}.mp3"
    mp3_file_name_new=${mp3_file_name_new//"_.mp3"/".mp3"}
    echo "$mp3_file_number of $mp3_files_total: $mp3_file_name_new";

    mp3_file_bitrate=`ffmpeg -i "${mp3_file}" 2>&1 | grep Audio | awk -F", " '{print $5}' | cut -d' ' -f1`
    mp3_file_bitrate="${mp3_file_bitrate}k";

    ffmpeg -i "$mp3_file" -vn -ar 44100 -ac 2 -ab $mp3_file_bitrate -codec:a libmp3lame -map_metadata 0 -id3v2_version 3 -write_id3v1 1 -f mp3 "${result_dir}/${mp3_file_name_new}" > /dev/null 2>&1
    mp3_file_number=$((mp3_file_number + 1))
done

end_date=`date`

echo "Start date: $start_date"
echo "Finish date: $end_date"

exit 0