#!/bin/bash
# jonen@mitschang.net
# TODO: output filename not music.mp3 but VideoName.mp3

# usage
url=$1
if [ -z "$url" ]; then
    echo "Downloads video from google video / youtube etc. and extracts the"
    echo "audio stream as mp3."
    echo "  Usage: $0 URL"
    echo "  URL is sth. like http://youtube.com/watch?v=..."
    exit
fi

# check binaries
if ! which clive > /dev/null; then
    echo "clive not found. install clive"
    exit
fi
if ! which mplayer > /dev/null; then
    echo "mplayer not found. install mplayer"
    exit
fi
if ! which lame > /dev/null; then
    echo "lame not found. install lame"
    exit
fi

# download
fileName=music
if ! clive -o --output-file=/tmp/$fileName.flv $url ; then
    echo "ERROR: Could not download $url."
    exit
fi

# extract wave file
mplayer /tmp/$fileName.flv -ao pcm:file=/tmp/$fileName.wav -vo null

# convert to mp3
lame /tmp/$fileName.wav $fileName.mp3

# delete temp files
rm /tmp/$fileName.flv /tmp/$fileName.wav

