Geekuprising.com Logo
Home Youth Debate About Us Clients Services Technologies Code
You are here:: Code > Audio > Streaming MP3/OGG Server
spacer
Browse

Streaming MP3/OGG Server

Geeks only here! This is a simple, short mod_perl handler that recursively traverses a directory, looking for MP3 and OGG files. It adds these files to an array, and then prints the array along with the "audio/x-mpegurl" mime header, so that the list is opened properly in any number of MP3 players.

Perl amazes me in how succinct and powerful it can be. This whole module is less than 40 lines of code!

Save the PlayListServer.pm perl module into a directory accessible by your apache server. Edit your Apache httpd.conf file to include the following lines, tailored to your configuration. These directives can go in <Virtualhost> containers, too.

In httpd.conf:

<Location '/mp3/'>
	PerlRequire '/www/dan/modules/PlayListServer.pm'
	PerlHandler PlayListServer
</Location>

The perl module PlayListServer.pm:

package PlayListServer;
use strict;
use File::Find;
use vars qw/ $path_to_webroot $mp3path $servername/;

$|=0;

sub handler{
	my $r=shift;
	my $s = $r->server;
	$mp3path='/mp3/';
	$path_to_webroot='/www/dan';
	$servername=$s->server_hostname;
	$r->content_type('audio/x-mpegurl');
	$r->send_http_header();
	find(\&make_list_to_print,$path_to_webroot.$mp3path);		
	return 200;
}

sub make_list_to_print{
	my $files;
	if (($File::Find::name =~ /\.ogg|\.mp3$/io)){
		my $temp = $File::Find::dir.'/'.$_;
		$temp =~ s/$path_to_webroot(.*)/$1/io;
		$temp =~ s/ /%20/og;
#		push @files, 'http://'.$servername.$temp;
		$files.= 'http://'.$servername.$temp."\n";
	} 
	my @files=split(/\n/,$files);
	my @sort_files=sort {uc($a) cmp uc($b)} @files;
	map{print "$_\n"}@sort_files;
}

1;

Discuss this Article!

Copyright 2004 © Geekuprising Internet Consultants