saransk 19.11.2011 16:23 QIP

A friend of mine wrote this nifty perl script that streams a random mp3 file from a playlist:

#!/usr/bin/perl

# mp3 streamer, written in perl.

# two support files are required:
# titles
# one title per line, chosen at random
# mp3.lst
# one record per line, tab delimited
# pathname length(in seconds) bitrate(kbps) title

# things to add:
# rate limiting (so a lynx -dump http://host :port > /dev/null
# won't saturate the upstream bandwidth
# mid-stream title changing
# multiple playlists

$playlist = "mp3.lst";
$titles = "titles";
$buffer = 10; #buffer length in seconds

sub getmp3
{
$file="mp3.lst";
my $mp3="";

do
{
open (MP3, $file) or die "JAQ 404 NO STREAM GO AWAY\n";
rand($.) < 1 && ($mp3 = $_) while <MP3>;
close MP3;
chomp $mp3;
($f,$l,$r,$t) = split /\t/, $mp3;
}
until -f $f;

return ($f,$l,$r,$t);
}

($prog = $0) =~ s/.*\///;
open (TITLE, $titles) or die "JAQ 404 NO STREAM GO AWAY\n";
rand($.) < 1 && ($title = $_) while <TITLE>;
close TITLE;
chomp $title;

($pathname,$ln,$br,$name)=getmp3;
$br=128 unless $br;

if ($name)
{
$mp3=$name;
}
else
{
($mp3=$pathname) =~ s/.*\/(.*)\.mp3/$1/;
$mp3=~s/_/ /g;
$mp3=~s/%20/ /g;
$mp3=~s/-/ — /g;
}

print "JAQ 200 OK\nx-audiocast-name:$title $mp3\n\n";

while (1)
{
$out=0;
$start=time;
open (MP3, $pathname) or die "\0\nEND OF STREAM GO AWAY\n";
print stderr "$prog: pid $$ $pathname\n";
while (<MP3> )
{
print;
$out += length;
$pause = $start — time + int ($out/($br*125)) — $buffer;
# the 125 is a magic number: it converts kilo-bits-per-second
# to bytes-per-second
#print stderr "pid $$ -> \$out: $out; \$br: $br; \$pause: $pause\n";
sleep $pause if ($pause>0);
}
$o=$pathname;
do {($pathname,$ln,$br,$name)=getmp3;} until $o ne $pathname;
$br=128 unless $br;
}

It's started using tcpserver -v 0 3125 ./streamer

Could this be made simpler/better in python?

Do you really want to delete ?