WWW FAQs: How do I embed sound and music in a web page?

2006-06-26: the easiest way to distribute sounds and music on the web is by simply linking to an audio file in MP3 (.mp3 file) format. If you have music in General MIDI format, .mid files are also widely supported. See the articles how do I convert my music to MP3 format? and how do I record an MP3 file? for more information on producing MP3-format audio files.

It is also possible to embed these files in the page so that they play in the background automatically. But this should be done with great care not to annoy the user. If you are convinced that an endlessly looping song is a good thing for your web page, force yourself to sit there and listen to it loop for a good 20 minutes or so while you try to read. It is difficult to overestimate how annoying bad background music can be!

File Format Choices

For very short sound samples (a few seconds or less), .wav files are appropriate. If your music is already in MIDI format, you can simply link to your .mid file. For music recordings, the .mp3 format is by far the most widely known and your visitors are very likely to have a compatible player.

Linking Directly to Audio Files

You can invite a user to play an audio file with a simple link like this:

<a href="mysong.mp3">Listen to my band's latest release now!</a>

Of course you must actually create mysong.mp3 in the first place, and upload it to your web hosting space, placing it in the same folder with the page. If you have not recorded or edited your sound files yet, I recommend Audacity, an excellent piece of free, open-source software that does a fine job of recording and editing audio files. It is suitable for both simple recordings and elaborate multitrack songs.

If you want to use Audacity to create low-bitrate MP3 files, you might experience a problem that makes your MP3 sound like "chipmunks" in Flash Player. Fortunately there is an easy fix for this. For more information, see the article why do my MP3 files sound bad in Flash Player?
Embedding Audio Files To Play in the Background

There are many ways to do this, offering various degrees of control and compatibility. In the past I've recommended embedding the music file directly with the <embed> or <object> element, and not specifying what player should be used. This works all right for one song, but leads to issues, when you want more than one, and also limits how much control you have over the presentation.

Ideally, the major embedded media players - RealPlayer, Windows Media Player, and QuickTime - would agree on a standard way to "remote-control" what's going on. Then we could use JavaScript and HTML to create our own "music player" look and feel. Or at the very least, successfully fetch the title of the currently playing song!

Unfortunately, the big players have never come to agreement on this. So right now, we simply can't do that reliably and consistently with the three major media players. While they work okay for embedding just one song, they start to disappoint the moment you get past that level. So I don't recommend them.

Does that mean we're stuck? Heck no! Fortunately, Flash Player is the most popular web browser "plug-in" of all, reaching roughly 97% of all users. Those who don't have it are usually in work environments where all plug-ins are forbidden anyway. And unlike the three players that are dedicated exclusively to playing sound and video, Flash Player was always intended to give the designer lots of control. In fact, support for MP3 music in Flash Player was originally intended to jazz up interactive Flash "applets" and games.

What does that mean for us? It means that by using Flash, we can get excellent control over the appearance and behavior of our in-page music player.

"Open-source Flash applet? How is that possible?" The SWF file format used by Flash applets is a quasi-open standard. And Adobe doesn't prevent you from redistributing your Flash applet as open source.
While it's true that Adobe/Macromedia's Flash Professional software costs a pretty penny, other people have already created free, open-source Flash-based music player "applets" that you can embed in your own page. The best of these is XSPF Web Music Player, a simple, free music player applet that gets the job done. And since that software is open source, others have extended it to support useful features like shuffle play. I'll be pointing you to the download page for one of those extended versions.

Embedding Music With Flash And XSPF Web Music Player

Ready to go? Great! Here are the steps to add music to your web page with Flash and the XSPF Web Music Player.

1. Download my enhanced version of the XSPF Web Music Player software. Just follow the instructions on that page to fetch a zip file that contains both the "extended" version, which displays a playlist, and the "slim" version, which just shows the currently playing song.

2. Open up the "compressed folder" (zip file) you've just downloaded. Extract it to your hard drive with "extract all files," then open the folder you've extracted it to. There will be two sub-folders, "Extended" and "Slim." Open the one you prefer. Now locate the file xspf_player.swf (or xspf_player_slim.swf). Windows users probably won't see the .swf part of the name - just don't use the .as or .fla file. If you're not sure which is which, right-click and pick "Properties" to show more complete information.

3. Upload xspf_player.swf (or xspf_player_slim.swf) to your website and drop it in the same folder with your MP3 files. (You could put it somewhere else, but this tutorial will assume it is in the same folder.) Usually you can do this by dragging and dropping to your favorite file transfer program.

4. With Notepad or another text editor, create a simple "playlist" file and save it with the name: test.xspf

The playlist file should look like this. Notice the title element, which should name your band and album (or any other heading you consider appropriate), the location element for each track, which should specify the name of the .mp3 file (you can use a full URL here if the .mp3 file is not in the same folder), and the annotation element for each track, which should give the name of the song so the user can see what they are listening to. You can also specify an image element, which provides a URL to an image to be displayed in the box to the left of the song (in the larger "extended" player).

<?xml version="1.0" encoding="UTF-8"?>
<playlist version="1" xmlns = "http://xspf.org/ns/0/">
  <title>My Band Rocks Your Socks</title>
      <title>Name Of Song A</title>
      <title>Name Of Song B</title>
      <title>Name Of Song C</title>
      <title>Name Of Song D</title>

5. Upload the playlist file, test.xspf, to your website as you would any other file.

6. Add the following code to your web page. This tutorial assumes your web page is in the same folder with your playlist file and xspf_player.swf:

<object type="application/x-shockwave-flash" width="400" height="170"
<param name="movie" value="xspf_player.swf?playlist_url=test.xspf" />

Note: I've set the width and height as suggested on the XSPF Web Music Player web page, but you can set them larger if you wish. If you are using the slim player, you'll set the height attribute quite a bit lower.

"The data attribute and the param name="movie" element carry the same information. Do I need both?" Yes. Flash is embedded differently in different web browsers.
7. Refresh the page in your browser. Your music player is up and running!
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, rename your XSPF file and change the name under which you load it in your web page. Clearing the cache may also be sufficient.

If It Doesn't Work

1. Make sure you uploaded the .swf file.

2. Make sure you uploaded your .xspf file. You did make one, right? If not, go back and read the instructions and do a thorough job.

3. Make sure you uploaded your .mp3 files.

3. If you are sure your HTML is correct and your browser shows the player but refuses to play the songs, it is possible that your web server doesn't allow files with a .xspf extension to be served. You can work around this by renaming your .xspf file to .txt. If you do so, you must change .txt to .xspf in both places where it appears in the object element.

Fine Tuning: Repeat Play, Autoplay, Shuffle Play, Images and Autoresume

Why doesn't the music play immediately? Because, by default, XSPF Web Music Player doesn't start playing until the user asks it to by clicking the "Play" arrow. A lot of people think this is a good thing because unwanted music is annoying and can get people in trouble at work or school. But if you really want the music to start right away, add &autoplay=1 to the end of the data and value URLs above, like this:


If you just want to load the playlist (your .xspf file) before the user clicks on the player, you can do that too:


You can also repeat the playlist (or repeat the song, if the playlist contains only one song) by setting repeat_playlist to 1. And you can limit the total number of songs played in this way by setting playlist_size. You can even set the player to automatically shuffle the playlist order by setting shuffle to 1 (only available with my version, or the Lacy Morrow version mine is based upon). All of these parameters can be used together - just be sure to separate them with & and set them the same for both data and param name="movie".

A new feature you'll find in my enhanced version of the player is the autoresume option. This option allows the music to resume from the same point when the user follows links from page to page on your site. Since the old page must be unloaded before the new one is loaded, there is a slight gap. But it's a big improvement over music that starts over and over at the beginning. Just add &autoresume=1 to the end of the data and value URLs above, like so:


Note that I have also specified autoplay here. Most users who want autoresume will probably also want autoplay, but you can still have the autoresume behavior without autoplay. Once the user does decide to manually start the music playing, the autoresume behavior kicks in as they move from page to page.

If you are using autoplay, I recommend also using autoresume, because it doesn't just remember what's playing - it also remembers that the user has clicked "stop" or "pause" and doesn't start the music again as the user moves from page to page. The more you honor your visitor's choices, the more they will like your site.

What about that box to the left of your song in the "extended" player? As I mentioned, you can put an image corresponding to each song in that box by adding an image element to each track element in your XSPF file.

Alternatively, if you have a single image that's appropriate for all of your songs, you can set one up via the main_image parameter. In this example, the file cover.jpg is fetched from the same folder where the page is located:

width="600" height="200"
value="xspf_player.swf?playlist_url=playlist.xspf&main_image=cover.jpg" />

If your image is larger than the box, it will be automatically resized to fit.

Alternate Method: For MIDI Files And Flash Haters

This is a great way to embed one or more songs in a web page. But maybe you have MIDI files, which this method can't support. Maybe you just hate Flash. And maybe you just want to know how to do it in a more generic way, without forcing the use of any particular player. This example shows how to do that.

The following example accommodates browsers all the way back to Netscape 4.

Does the audio file have to be on the same site? No. Much like the src attribute of an img element, the src attribute of the EMBED element can point to any site you like with a full URL, such as http://www.example.com/examples/mysong.mp3.

<embed src="mymusic.mid"

Why use the old embed element instead of object? Because the embed element supports the loop option. The object element doesn't reliably support it across all major browsers, not even if you correctly place it in a param element inside the object. I follow standards wherever I can, but at the end of the day, things have to work!
Notice that the loop attribute has been set to true. Think carefully before you do this. Your visitors may appreciate your music more if you do not force them to listen to it over and over!
You should be able to use loop="5" to loop five times rather than forever. Unfortunately, in our tests, this does not work properly in Firefox. So for the time being your reliably-working options appear to be looping forever, and not looping at all.

In this case, the embedded song file is a MIDI file called mymusic.mid; but you can do the same trick with MP3 files.

Sometimes the Firefox browser, especially on Windows, will ask the user to install a plug-in that she already has. And installing the plug-in still doesn't solve the problem. This happens when QuickTime or another plug-in is not configured as the player of choice for the right MIME types.

If your users have this problem, just send them to the article Why does Firefox want me to install a plug-in I already have?

If the music does not play for you, and your browser is not asking you to download a plugin with which to play it, then your web server might not be aware of the correct mime type for MIDI or MP3 files. Your server administrator can adjust this for you. All recently released web server software ships standard with the correct settings for these files.

If you are the web server administrator, and you are running the Apache server, you can add the following line to your httpd.conf file:

AddType audio/x-mp3 .mp3
You will then need to signal Apache to reload its configuration files and restart.
Insert the embed element where you want the player to appear in your page. If you are hiding the player, the embed element still needs to be somewhere inside the body element.

If your web server administrator will not cooperate, you can still save the day by adding type="audio/x-mp3" to your <embed> element. Although it's ugly, this method does allow the designer to override badly configured MIME settings on the web server.

See also how do I play sound from JavaScript, how do I play a list of several MP3 songs on a web page, and how do I play songs in a random order on my 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!