#!/bin/bash # ========================================================= # Script for resampling audio files to cd resolution # and automatically adjusting the peak level # # Dependencies: SoX, flac, bash, awk # ========================================================= function printHelp() { echo 'Usage: cmd [OPTION]... FILES' echo 'Options:' echo ' --help (-h): Print this page' echo ' --no-gain-adjustment (-ng): Disable gain adjustment, no peak level changes' #echo ' ' #echo ' ' #echo ' ' } cmd=sox_ng iterations=2 gainAdjustment=true destination='resampled' gain='0.00' safeGuard='0.00' targetLevel='0.01' # -0.01 dB files=() if [[ -z "${*}" ]]; then echo 'No arguments given.' printHelp exit fi for argument in "${@}"; do if [[ "${argument}" == '-h' ]] || [[ "${argument}" == '--help' ]]; then printHelp exit elif [[ "${argument}" == '--no-gain-adjustment' ]] || [[ "${argument}" == '-ng' ]]; then echo 'Disabling gain adjustment...' iterations=1 gainAdjustment=false elif [[ ! -r "${argument}" ]]; then echo "The argument or filepath provided \`${argument}\` does not exist, quitting..." exit else files+=("${argument}") fi done mkdir -vp "${destination}" for (( i = 0 ; i < iterations ; i++ )); do for file in "${files[@]}"; do cmdOutput="$("${cmd}" -DV4 "${file}" -b 16 -t flac "resampled/${file}" gain "${safeGuard}" rate -u -L -d 33 -b 96 44100 gain "${gain}" 2>&1)" clipping="$(echo "${cmdOutput}" | grep -i 'clipped')" echo "${cmdOutput}" if [[ -n "${clipping// /}" ]]; then echo 'Audio clipped, resetting...' safeGuard="$(echo "${safeGuard} 0.30" | awk '{ print $1 - $2 }')" gain='0.00' i=-1 break fi done if [[ "${gainAdjustment}" == true ]] && [[ "${i}" != -1 ]]; then peakLevel="$(cd "${destination}" && "${cmd}" "${files[@]}" -n stats 2>&1 | grep 'Pk lev' | awk '{ print $4 }')" if [[ -z "${peakLevel// /}" ]]; then echo 'Error invoking SoX, check dependencies and audio files' exit fi echo -e "\nTracks peak level: ${peakLevel} dB" gain="$(echo "${targetLevel} ${peakLevel} ${gain}" | awk '{ print $3 + (($1 + $2) * -1) }')" echo "Applied gain: ${gain} dB" fi done