#!/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/shawn/PodCasts #directory where to save the file
TEMPDIR=/tmp

# Don't edit anything below this line
#######################################################
DATE=`date +%d-%b-%Y`  # Save the date as DD-Mmm-YYYY
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
