Mp3 converter script

Jul 28, 2020 Script System

You may have a series of flac or very high quality Mp3s that you wish to resample/transcode to 192kb/s MP3. Yes I know, audiophiles may leave the room now…

Below is a small bash script that uses ffmpeg and id3cp to resample existing files. It will convert all files unless they have a lower bitrate that the one specified.

Requirements

  • ffmpeg
  • id3cp (libid3-tools)

The script

Save the following as a bash file (eg: /usr/local/bin/audio2mp3) and make it executable (chmod 755 <file>). Feel free to edit the output QUALITY value if you prefer something other than 192kb/s.

Note: This will overwrite your exiting files, so test first.

#!/bin/bash

## Config ##
ffmpeg=/usr/bin/ffmpeg
id3cp=/usr/bin/id3cp
QUALITY=192

if [[ ! -f $ffmpeg ]]; then
    echo "$ffmpeg not found. Exiting"
    exit
fi
if [[ ! -f $id3cp ]]; then
    echo "$id3cp not found (libid3-tools). Exiting"
    exit
fi


### End Config ##
if [ $# -lt 1 ]; then
  echo "    Usage:  `basename $0` <audio-files>" 1>&2
  exit 1
fi

FFMPEG_QUALITY=$(($QUALITY * 1000))

while [ -n "$1" ]; do

    filename="$1"
    if [[ -f $ffmpeg ]]; then
        SRC_BR=$($ffmpeg -i "${filename}" 2>&1| grep "Audio: mp3" | cut -f13 -d " ")
        if [ $SRC_BR \> $QUALITY ]; then
            echo "Converting \"${filename}\" from ${SRC_BR}kb/s to ${QUALITY}kb/s"
            output="${filename}.converted.mp3"
            $ffmpeg -i "${filename}" -b:a $FFMPEG_QUALITY "${output}" -vsync 2 -loglevel error
            $id3cp "${filename}" "${output}"
            mv "${output}" "${filename}"
        else
            echo "Source quality of \"${filename}\" is not higher than ${QUALITY}kb/s (${SRC_BR}kb/s), skipping conversion"
        fi
    else
        echo "${filename} not found."
    fi
shift;

done

Usage

audio2mp3 my-super-huge-file.mp3

or if you want to convert all MP3s in your current directory:

audio2mp3 *.mp3

Comments