Want to downsample all of your mp3s so they all fit on your phone?

If you install lame and mp3info into your Mint (or Debian) Linux box, the following code will help you downsample your music collection from one directory to another.

#!/bin/bash

  INPUT_DIR="/data/PhoneMusic1"
 OUTPUT_DIR="/data/downsampled"
ARCHIVE_DIR="/data/OriginalMusicArchive"
NEW_BITRATE=128
SAVINGS=0

IFS=$'*'

cd ${INPUT_DIR}

for ALBUM in *
do

  if [ "${ALBUM}" != "$0" ]
  then

    ORIGINAL_SIZE=$(du -sch ${INPUT_DIR}/${ALBUM} | grep total | awk -F'M' '{print $1}')

    cd    "${INPUT_DIR}/${ALBUM}"
    pwd

    if ! [ -d "${OUTPUT_DIR}/${ALBUM}" ]
    then

      mkdir "${OUTPUT_DIR}/${ALBUM}"

    fi

    for TRACK in *.mp3
    do

      if ! [ -f "${OUTPUT_DIR}/${ALBUM}/${TRACK}" ]
      then

        OLD_BITRATE=$(mp3info -r a -p "%f %r\n" ${TRACK} | awk '{print $NF}'| awk -F'.' '{print $1}')

        if [ ${OLD_BITRATE} -gt ${NEW_BITRATE} ]
        then

          echo "Downsampling ${OLD_BITRATE}->${NEW_BITRATE}: Track: ${TRACK}"
          lame --mp3input -b ${NEW_BITRATE} -q0 "${TRACK}" "/tmp/${TRACK}" > /dev/null 2>&1
          mv "/tmp/${TRACK}" "${OUTPUT_DIR}/${ALBUM}"

        else

          echo "Low Sample Rate: ${OLD_BITRATE}, ${OUTPUT_DIR}/${ALBUM}/${TRACK}"
          cp "${TRACK}" "${OUTPUT_DIR}/${ALBUM}/${TRACK}"

        fi

      else

        echo "Previously Converted: ${OUTPUT_DIR}/${ALBUM}/${TRACK}"

      fi

    done

    NEW_SIZE=$(du -sch ${OUTPUT_DIR}/${ALBUM} | grep total | awk -F'M' '{print $1}')
    DELTA=$((${ORIGINAL_SIZE}-${NEW_SIZE}))
    SAVINGS=$((${SAVINGS}+${DELTA}))

    echo "Original Size: ${ORIGINAL_SIZE}M, New Size: ${NEW_SIZE}M, Delta: ${DELTA}M & Savings: ${SAVINGS}M"

    cd "${INPUT_DIR}"
    mv "${ALBUM}" "${ARCHIVE_DIR}"

  fi

done

Author: Andrew

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.