On-demand MP3 streaming

The problem: small upload at home (ADSL, 80kb/s), big FLAC files on HDD, serve them via www so a remote client can play them realtime – solution: on-demand mp3 streaming, which automatically converts FLAC file streams to MP3 data.

So if a client wants a FLAC file from the webserver, it returns the file in MP3 format. The client must handle that MP3 data is coming under the FLAC extension (ffmpeg or vlc does this, I use them as clients).


I’m using lighttpd as the webserver. I added these lines into lighttpd.conf:

1
2
3
4
5
6
7
8
9
    $HTTP["host"] == "puttony.home.nonoo.hu" {
            url.rewrite-once = ( "(.*)(\.flac|\.fla|\.ape)$" => "/2mp3.php?src=/home/storage4/backups/nonoo$1$2" )
    }

    $HTTP["remoteip"] !~ "::ffff:217.20.130.34|::ffff:192.168.|::ffff:127.0.0.1" {
        $HTTP["url"] =~ "^/mp3/" {
            url.access-deny = ( "" )
        }
    }

The first section rewrites URLs which point to a .flac, .fla or .ape file and redirects these queries to the PHP script called 2mp3.php. I store my music files under /home/storage4/backups/nonoo. The second section only allows access to my mp3 folder from the specified IP address ranges.

The 2mp3.php script looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
    $src = $_GET['src'];
    if( preg_match( '/^http:\/\//', $src ) )
        $src = str_replace( array( '%2F', '%3A' ), array( '/', ':' ), rawurlencode( $src ) );

    header( 'Content-Type: audio/mpeg' );

    $ffmpeg = "/usr/local/bin/ffmpeg -i '$src' -vn -acodec libmp3lame -vol 200 -ab 320000 -ar 44100 -ac 2 -f mp3 -";

    $handle = popen( $ffmpeg, 'r' );
    while( !feof( $handle ) )
    {
        $read = fread($handle, 4096);
        echo $read;
    }
    pclose( $handle );
?>

As you can see, I’m using ffmpeg in a pipe as the transcoder. It can handle various inputs given in the ?src= parameter, so it’s not limited only for the files on my HDD.

Name (required)
E-mail (required - never shown publicly)
Webpage URL
Comment:
You may use <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> in your comment.

Trackback responses to this post

About me

Nonoo
I'm Nonoo. This is my blog about music, sounds, filmmaking, amateur radio, computers, programming, electronics and other things I'm obsessed with. ... »

Twitter

Listening now

My favorite artists