Script "convert-mp3s.sh"
#!/bin/sh

[ $# -eq 2 ] || echo "Usage: ${0} < directory > < [bitrate] | [ogg] >" ; [ $# -eq 2 ] || exit 1
[ -d "${1}" ] || echo "ERROR: directory does not exist. Abort." ; [ -d "${1}" ] || exit 1

ffmpeg_is_present=""
which ffmpeg 1>/dev/null 2>&1 && ffmpeg_is_present="yes"
[ -z ${ffmpeg_is_present} ] && echo "WARNING: ffmpeg is not installed!"

ogg_mode=""
[ "${2}" = "ogg" ] && ogg_mode="yes"
mpg321_oggenc_are_present=""
which mpg321 1>/dev/null 2>&1 && which oggenc 1>/dev/null 2>&1 && mpg321_oggenc_are_present="yes"
[ -z ${mpg321_oggenc_are_present} ] && echo "WARNING: mpg321 and/or oggenc are not installed!"

cd "${1}"
kbpsDirName="${2}_kbps"
[ -z ${ogg_mode} ] || kbpsDirName="Play Ogg"
mkdir -p "${kbpsDirName}"
[ -d "${kbpsDirName}" ] && echo "Created directory:" "${1}/${kbpsDirName}"

listOfMP3s=`find "${1}" -type f -print0 2>/dev/null | xargs -0 file --mime | grep "audio/mpeg" | cut -d':' -f1`
if [ -z "${listOfMP3s}" ]; then
  echo "Sorry, no MP3 files found in ${1}"
  rmdir "${kbpsDirName}" && echo "Removed directory:" "${1}/${kbpsDirName}"
else
  doConvert="yes"
  convertStr="File"
  if [ -z ${ogg_mode} ]; then
    convertStr="Converting MP3 file to {2} kbps"
    [ -z ${ffmpeg_is_present} ] && doConvert=""
  else
    convertStr="Converting MP3 file to Ogg"
    [ -z ${mpg321_oggenc_are_present} ] && doConvert=""
  fi
  [ -z ${doConvert} ] && convertStr="Found MP3 file"

  echo "${listOfMP3s}" | while read line
  do
    fileToConvert=`echo "${line}" | sed "s|${1}|.|"`
    printf "%s: %s" "${convertStr}" "${fileToConvert}"
    if [ -z ${doConvert} ]; then
      echo "!"
    else
      rm -f raw 1>/dev/null 2>&1
      printf "..."
      currDirName=${kbpsDirName}/`dirname "${fileToConvert}"`
      mkdir -p ./"${currDirName}"
      ##[ -d "${currDirName}" ] && printf " [ (DEBUG) %s: %s ] " "Created directory" "${1}/${currDirName}"
      if [ -z ${ogg_mode} ]; then
        newFileName=`basename "${fileToConvert}"`
        ffmpeg -i "${fileToConvert}" -ab ${2} ./"${currDirName}"/"${newFileName}" 1>/dev/null 2>&1
      else
        newFileName=`basename "${fileToConvert}" | sed 's/.mp3//'`.ogg
        mpg321 "${fileToConvert}" -w raw 1>/dev/null 2>&1 && \
          oggenc raw -o ./"${currDirName}"/"${newFileName}" 1>/dev/null 2>&1
      fi
      if [ $? -eq 0 ]; then echo " ok!"; else echo " fail"; fi
      rm -f raw 1>/dev/null 2>&1
    fi
  done
fi
Unless otherwise stated, the content of this page is licensed under GNU Free Documentation License.