Question

I need to know the average volume of an mp3 file so that when I convert it to mp3 (at a different bitrate) I can scale the volume too, to normalize it...

Therefore I need a command line tool / ruby library that gives me the average volume in dB.

Was it helpful?

Solution

You can use sox (an open source command line audio tool http://sox.sourceforge.net/sox.html) to normalize and transcode your files at the same time.

EDIT

Looks like it doesn't have options for bit-rate. Anyway, sox is probably overkill if LAME does normalization.

OTHER TIPS

You can use LAME to encode to mp3. It has options for normalization, scaling, and bitrate. LAME also compiles to virtually any platform.

http://mp3gain.sourceforge.net/ is a well thought out solution for this.

I wrote a little wrapper script, based on the above input:

#!/bin/sh

# Get the current volume (will reset to this later).
current=`amixer -c 0 get Master 2>&1 |\
    awk '/%/ {
              p=substr($4,2,length($4)-2);
              if( substr(p,length(p)) == "%" )
                 {
                 p = substr(p,1,length(p)-1)
                 }
             print p
             }'`

# Figure out how loud the track is.  The normal amplitude for a track is 0.1. 
#   Ludicrously low values are 0.05, high is 0.37 (!!?)
rm -f /tmp/$$.out
/usr/bin/mplayer -vo null -ao pcm:file=/tmp/$$.out $1 >/dev/null 2>&1
if [ $? = 0 ] ; then
    amplitude=`/usr/bin/sox /tmp/$$.out -n stat 2>&1 | awk '/RMS.+amplitude/ {print $NF}'`
fi
rm -f /tmp/$$.out

# Set an appropriate volume for the track.
to=`echo $current $amplitude | awk '{printf( "%.0f%%", $1 * 0.1/$2 );}'`
echo $current $amplitude | awk '{print "Amplitude:", $2, "  Setting volume to:", 10/$2 "%,  mixer volume:", $1 * 0.1/$2}'
amixer -c 0 set Master $to  >/dev/null 2>&1

mplayer -quiet -cache 2500 $1

# Reset the volume for next time.
amixer -c 0 set Master "$current%"  >/dev/null 2>&1

It takes an extra second to start up playing the file, and relies on alsamixer to adjust the volume, but it does a really nice job of keeping you from having to constantly tweak the master volume. And it doesn't really care what the input format is, since if mplayer can play it at all, it can extract the audio, so it should work fine with MP3, Ogg, AVI, whatever.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top