Monday, May 04, 2009

How to capture and record streaming internet audio in Linux

For this exercise, lame, sox and mplayer will be used to capture audio from the streaming internet feed of Washington, DC based radio station WMAL. First, save the following script into whatever bin directory you feel comfortable with under a name such as record.sh:

#!/bin/bash
#
# record.sh
#
# Use mplayer to capture the stream
# at $STREAM to the file $FILE
#
# example: record.sh my_radio_show 60 mms://someserver.com/stream

DIR=/home/jim/Music/PodCasts #directory where to save the file
TEMPDIR=/tmp

# Don't edit anything below this line
#######################################################
DATE=`date +%Y-%m-%d` # Save the date as YYYY-MM-DD
YEAR=`date +%Y` # Save just the year as YYYY
NAME=$1
DURATION=$2 # enough to catch the show, plus a bit
STREAM=$3
TEMPFILE=$TEMPDIR/$NAME-$DATE
FILE=$DIR/$NAME-$DATE # Where to save it

# Capture Stream
mkfifo $TEMPFILE.wav
mkfifo $TEMPFILE-silenced.wav

# The lame settings below are optimized for voice encoding
# The sox command below strips out any silent portions
lame -S -a -m m --ty "$YEAR" --vbr-new -V 9 --lowpass 13.4 --athaa-sensitivity 1 \
--resample 32 $TEMPFILE-silenced.wav $FILE.mp3 >/dev/null &
sox $TEMPFILE.wav -c 1 $TEMPFILE-silenced.wav \
silence 1 0.2 0.5% -1 0.2 0.5% >/dev/null&
/usr/bin/mplayer -really-quiet -cache 500 \
-ao pcm:file="$TEMPFILE.wav" -vc dummy -vo null \
-noframedrop $STREAM >/dev/null&

sleep 5
# get the pid of all processes started in this script.
PIDS=`ps auxww | grep $TEMPFILE | awk '{print $2}'`

# the & turns the capture into a background job
sleep `echo ${DURATION}*60 | bc` # wait for the show to be over
kill $PIDS >/dev/null # kill the stream capture
rm $TEMPFILE.wav
rm $TEMPFILE-silenced.wav


I wish I could claim this nifty little script as my own creation, but I found it somewhere on the internet and modified it to suit my own needs.

This script can be invoked using the command:

/home/jim/bin/record.sh Ric_Edelman 120 http://citadelcc-WMAL-AM.wm.llnwd.net/citadelcc_WMAL_AM

where the first parameter is the name of the radio show, the second the number of minutes to record and the third the URL of your favorite radio stream.

After testing to ensure everything works properly, it is time to set up the crontab entries for recording your shows. I use gnome-scheduler so I don't miss a show no matter what I'm doing:



The details of how one recording is set up:



Hope this proves useful.

No comments: