WWW FAQs: How do I play songs in a random order on my web page?

2006-06-26: This is much easier than it used to be! First, create a playlist of songs and embed a player in your page with the, free, open-source, Flash-based XSPF Web Music Player. Make sure you use my version, available from my XSPF Player page, which includes Lacy Morrow's modifications to support a shuffle option. Lacy Morrow's own site unfortunately appears to be down as of this writing.

I explain how to use this player in the article How do I embed sound and music in a page?

Then, just make one change: add &shuffle=1 to the end of the player URL in the data attribute of the object element and the value attribute of the <param name="movie"> element. Now XSPF Web Music Player will automatically shuffle the songs - provided you have the Lacy Morrow version, as found via the link above. Really, it's that easy.

When you make changes to an XSPF file, clicking Reload or Refresh in your browser will not reload the XSPF file. You will not see your changes, even if you restart your browser. Yes, it's really annoying, but it seems to be a fact of life with Flash. To be sure you see the effect of your changes right away, rename your XSPF file, and change the name wherever it appears in your object element. Then reload the page.

Clearing your cache may also be sufficient.

Alternative Method: Without Flash

If you prefer not to use Flash on your site - and since 95% of all users have Flash and the Flash SWF file format is quasi-open these days, you should seriously consider using Flash - there is an alternative method.

To play songs in a random order, we need to create a randomized M3U playlist. Before you continue, I strongly recommend that you read how do I play a list of several MP3 songs on a web page? to understand the basics (see the non-Flash alternative portion of that article).

Now that you've read about playlists, you know that we need to create a .m3u file that lists the URLs of the songs we want to play. But how can we put those songs in a random order for every user? The answer: we'll use PHP. Using PHP code, we can easily open up a .m3u file, shuffle the songs with PHP's built-in shuffle function, and deliver the result to the web browser as a playlist. We'll use a very cool feature of PHP called PATH_INFO to avoid creating any temporary playlist files. See the technical notes at the end of this entry for details on how it all works.

PHP is a great choice for this job. But users who are required to use Perl/CGI or ASP programming for web development can still use the ideas presented here in their own code. And the PATH_INFO trick demonstrated here works just as well for Perl CGI programs. But if you are using a free web hosting service that doesn't allow any kind of server-side programming... well, back up and ask yourself again why you're not using the XSPF Web Music Player method, which doesn't require you to do any of this. If you're sure you have a good reason, then it's time to start paying for hosting that includes PHP support. Hosting services that include PHP can be really, really cheap these days. Less than $10 a month in fact. So skip a pizza once in a while and get a real web host. When you pay for your PHP hosting, the host doesn't stuff your page with annoying ads or, even worse, "spyware" programs that will make your visitors very angry.
Follow these steps to play MP3 files in a random order on your web page:

1. Create a playlist file called playlist.m3u containing all of the songs you want, in any order. See How do I play a list of several MP3 songs on a web page? for complete instructions on how to make a playlist file.

2. Upload playlist.m3u to your website. When you do, make a note of the file system path to playlist.m3u on the server. If your FTP program shows that the folder is /home/sites/yourname/www.example.com/examples/, then the path to playlist.m3u is /home/sites/yourname/www.example.com/examples/playlist.m3u. Note: this is NOT a URL. It is the place on the server's hard drive where the file lives. If you don't understand this, reread it until you do!

3. Create the file randomsongs.php, containing the following. There must be ABSOLUTELY NO BLANK LINES OR WHITE SPACES AT THE BEGINNING! Otherwise it will be too late for the script to output a playlist instead of an HTML page when that is appropriate.

 $playlist = "/home/sites/myname/www.example.com/examples/playlist.m3u";
 if ($_SERVER['PATH_INFO'] == "/playlist.m3u") {
  # This a request for the actual playlist.
 } else {
  # Fall through to end of script and display
  # the player HTML.
 function playlist() {
  header("Content-type: audio/mpeg");

  # Needed for PHP versions OLDER than 4.2.0 only.
  # If your host still has PHP older than 4.2.0, shame on them.
  # Find a better web host.

  # Fetch our list of songs from a file.
  $songs = file($playlist);
  # Now output the URLs in random order.
  foreach ($songs as $song) {
   # Remove newline and any other leading and trailing
   # whitespace from URL of song.
   $song = trim($song);
   echo "$song\n";
  # Now exit before any HTML is produced.
 # Needed only for very old versions of PHP,
 # see srand call earlier.
 function make_seed()
  list($usec, $sec) = explode(' ', microtime());
  return (float) $sec + ((float) $usec * 100000);

<title>MP3s Playing in Random Order</title>
<h1 align="center">MP3s Playing in Random Order</h1>
<embed src="/examples/randomsongs.php/playlist.m3u"

4. At the top of randomsongs.php change the setting of the $playlist variable to match the file system path of your playlist file... which you wrote down in step two.

5. randomsongs.php assumes you will be placing your PHP page in a folder on your website called /examples. If that's not right, change the src attribute of the embed element. DO NOT remove /playlist.m3u from the end of the URL. If you want to know why it's there, read the technical notes at the end of this entry.

5. Upload randomsongs.php to your web server.

6. Upload your .mp3 files if you have not already done so.

7. Access randomsongs.php with your web browser. In our example, the URL would be http://www.example.com/examples/randomsongs.php, but of course your URL will be different. Your songs will begin to play in a random order.

Insert the embed element anywhere inside the body element of your page. If you choose to make the player visible, place the embed element at an appropriate location within the page.

Congratulations, you're the proud owner of an HTML Shuffle. Much cheaper than the iPod Shuffle! (Just kidding, Apple.)

If your songs don't play:

1. Make sure you have successfully completed How do I play a list of several MP3 songs on a web page? first. Make sure you are successful with an ordinary playlist file before you move on to using randomsongs.php.

2. If you are using a very old version of PHP, or PHP compiled for CGI use instead of Apache module use, it's possible that $_SERVER['PATH_INFO'] doesn't work properly in your environment. With a little ingenuity, the script can be modified to create temporary .m3u files instead of outputting playlists directly to the browser.

Technical Notes

You could write a PHP page that creates a new .m3u file on the server for every visitor. Then your PHP code would output the HTML for a player that uses the src attribute of the <embed> element to point to that newly created file. But then you would have piles of temporary .m3u files lying around. And you would need more code to clean them up every so often. Yuck.

Fortunately, there's a simpler way.

PATH_INFO to the Rescue

When a user accesses, let's say, http://www.example.com/examples/mypage.php, the PHP code in mypage.php runs. That's not surprising to anyone.

But this might surprise you: when a user accesses http://www.example.com/examples/mypage.php/extrastuff, the user does not get an error. Instead, mypage.php still runs... and the "extra" part of the URL, /extrastuff, shows up in the PHP variable $_SERVER['PATH_INFO'].

How does this help us? We can use the src attribute of the embed element for our player to point right back to the PHP script... with /playlist.m3u tacked on to the end.

Before you blame our use of the MIME type audio/mpeg instead of audio/mpegurl for this pickiness about file extensions, you'd better read How do I play streaming audio on my web page? very carefully. In a nutshell, audio/mpegurl is the "right" way, but the fact is it doesn't work for lots of users.
That helps us in two ways:

First, even though they shouldn't do this and mime types should absolutely always tell browsers what to do, the fact is that many web browser/MP3 player combinations just won't accept a playlist unless the file appears to have a .m3u file extension. That means we need that /playlist.m3u at the end of the URL to make, for instance, Firefox for Windows happy.

Second, we can make this work for us by recognizing the /playlist.m3u part of the URL and generating the randomized playlist directly from PHP, writing it straight to the browser when the browser actually asks for it. No temporary files, no muss, and no fuss.

See also How do I embed sound and music in a page, How do I play streaming audio on my web page and How do I play a list of several MP3 songs on a web page.

Legal Note: yes, you may use sample HTML, Javascript, PHP and other code presented above in your own projects. You may not reproduce large portions of the text of the article without our express permission.

Got a LiveJournal account? Keep up with the latest articles in this FAQ by adding our syndicated feed to your friends list!