Transcoding HTTP mp3 streaming proxy in bash

Published on 29 September 2008

Here's how to make a proxy for streaming mp3s. It transcodes on-the-fly to 64kpbs MP3 using lame. When transcoding is finished, it calls the ./ script, which can either just delete the file, or potentially archive it so you don't need to transcode it again.

read method url version


echo -ne "HTTP/1.0 200 OK\r\nContent-type: audio/mpeg\r\n\r\n"

BR=64 #birate to transcode to.
mkfifo "$PIPE"

url=`echo "$url" | sed 's/\///'`
echo "** GET $url" >&2

nohup lynx --source "$url" \
    | (lame --preset cbr $BR --mp3input - - 2>/dev/null \
      && (echo "** Finished transcoding $url" >&2 ; \
          ./ "$OUTFILE"&))\
    | tee -i "$PIPE" > $OUTFILE &

cat < $PIPE
rm $PIPE

One interesting limitation seems to be the buffer size of a fifo pipe in linux. Even though the transcoding step is pretty quick, if a client is connected the transcoding only manages to fill the pipe a couple of hundred k ahead of what is being read.

The -i flag to tee means it ignores interrupts, and will finish transcoding the file and call the posthandler even if the client disconnects.

Run is like this:

$ while [ 1 ]; do nc -vlp 8080 -c './' ; done

Then hit up a url of your choice using your awesome new proxy:

$ URL=""
$ mpg321 "http://localhost:8080/$URL"

Not the most scalable solution, but a mildly amusing quick hack.

This article was published on: 29 September 2008
Tagged as:
blog comments powered by Disqus