#!/bin/sh

# A script to record internet radio broadcasts as mp3 files
# Written by Michael Miller on 2-Jan-2006
#
# Modified by James Williams Zavada on 4-Jan-2006
# to enhance the usage output so that it displays the
# actual script name and path no matter what it is

# Name of output directory (it must already exist)
DIR="$HOME/audio-streaming/"

if [ $# -lt 3 ]; then cat <<EOF

USAGE: $0 NAME LENGTH URL
   where NAME is file name for the saved recording
         LENGTH is the length of time to record (in minutes)
         URL is the url of the stream to be recorded
To time-shift a recording, run this script using the "at" command, e.g.
   \$   at 2:59pm next Tuesday
   at> record.sh "My_Favorite_Show" 32 "rtsp://someurl/show.ra"  

EOF

exit 1
fi

NAME="$1"
LENGTH="$2"
URL="$3"

# Aliases for streams can be put here
case "$URL" in
   "WCNY" ) URL="http://subscribe.streamguys.com/WCNYWEB" ;;
   "BBC4" ) URL="rtsp://rmlivev8bb.bbc.net.uk/farm/*/ev7/live24/radio4/live/r4_dsat_g2.ra" ;;
   *      ) ;;
esac

FILENAME="$DIR${NAME}_`date +%Y%m%d-%H%M`.mp3"

FIFO="$DIR$$.wav"
mkfifo $FIFO

mplayer $URL -ao pcm:file=$FIFO &>/dev/null &
PID=$!

(
lame -h $FIFO $FILENAME &>/dev/null
rm -f $FIFO
kill $$ &>/dev/null
) &

sleep `expr 60 \* $LENGTH`

kill $PID

