When offering an MP3 file for downloading, usually two files are stored in the server: the .mp3 file itself, and a small playlist file (.m3u) which tell the mp3 player to stream the .mp3 file. This script avoids the need of storing an .m3u file for each .mp3 file. It serves an .m3u playlist "file" to the client, created on the fly. You can test this script in the site of community radio KGNU; go to http://kgnu.org/ht/listings.html and click on any "Listen" icon.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#!/usr/bin/python # Create an m3u playlist file on the fly # Use the query string in the URI to create the file name in the playlist # This python script's extension is .m3u instead of .py, to fool the browser into opening an MP3 player # Despite its extension, the top line in this script makes it executable as a python script # Davide Andrea, KGNU 2/24/06 import cgi AudioPath = 'http://kgnu.net/audio/%s_%s.mp3' def Main(): #------------------ # Main procedure print "Content-type: text\n" # Note that its not text/html, as it would be for a web page uriQuery = cgi.FieldStorage() # Get the query string from the URI showCode = uriQuery.getfirst('show','') # From it, get the show name recDate = uriQuery.getfirst('date','') # and the date filePath = (AudioPath % (showCode, recDate)) # Assemble the file name and path print filePath # This is the content of the "file" served, that the MP3 player will see #------------------ # Main Main() # Do the main procedure
The script is called play.m3u Note that, although this is a Python script, its extension is not .py. but .m3u. This is to tell the browser to open the "file" with an mp3 player, and to tell the player that it's seeing a playlist. Yet, the server knows it's a python script because of the first line of the code, and because of its location in the cgi-bin folder.
The web page with the links to listen to the mp3 file contains links to the script, with the name of the show and the date specified in its query string.
For example, a complete URI to call the script is: http://kgnu.org/cgi-bin/play.m3u?show=MorningMagazine&date=2006-02-27
In our implementation, the script also logs the request (IP address, time and program accessed) and increments the number of times the program was heard, in a data base.