How To Play Sound

So, you want the visitor to listen to your music, no matter what kind of operating system, browser, media player he/she has. You've already tried various solutions found on the Net from Micky Mouse to Overkill Guru, but not one worked exactly the way a sound playing Web page is supposed to work.

This article shows you how to play sound on all major browsers and platforms, without having any extra Web development environment other than a text editor.

  What can a visitor expect?

  Historical Solutions

Basically, four HTML tags can make your page play sound; the BGSOUND backgrond sound tag, the A hyperlink, the EMBED, and the OBJECT tags. Other solutions involve either Javascript programming or even more sophisticated approaches. Let's deal with these HTML solutions first, then with a simple script.

1. Backgrond sound BGSOUND

Form:
<bgsound src="sample.wav" loop="-1">

BGSOUND is an Internet Explorer-only, non-standard tag. So, if you say "Forget about it" now, you are right. But there are more arguments against it. It loads the sound file when the page is loaded and after the full download, it starts to play without user intervention. The loop="-1" attribute makes the sound replay over and over. This is one of the most annoying solutions, so, I don't create an example here, as I do in the following solutions. It doesn't give the visitor any control. It's only "advantage" is that, unlike in some other sophisticated solutions, the sound stops immediately when the horrified visitor clicks away from the site.

2. Hyperlink A

Form:
<a href="sample.wav">Play Sample</a>

This is the simplest way and it almost always works with the three major browsers, Internet Explorer, Mozilla (Netscape/Firefox), and Opera. With most browser settings and file formats, it launches a media player. If no player application has been installed, the visitor probably has not played sound on this computer before. A reasonable visitor will not blame you that your site is the one that fails. The real drawback of this solution is that the sound usually doesn't start playing until it has been completely downloaded, and the downloading doesn't start until one clicks on the link. Some browsers combined with some media player applications try to stream the sound; i.e., start to play the sound before it is fully downloaded but it may stall later.

Here is an example: Play Sample

3. EMBED

Form:
<embed src="sample.wav" autostart="false" loop="false">
</embed>

The EMBED tag causes the sound file to be downloaded when the page is loaded, just like an IMG tag makes an image load. The browser then looks for a plug-in or for a built-in player. Internet Explorer has the least problem because its Windows Media Player is integrated in its newer versions. Mozilla prefers Quick Time as media player but it is an external application. RealOne (Real Audio Player) or WinAmp are alternative media players to plug in. EMBED is not a standard HTML or XHTML element, either, but all major browsers handle it very well.

Here is an example, which may not work on a networked computer in certain network settings and may cause an "Unable to establish connection to the server" message popping up. You may also need to click more than once to make it start:


4. OBJECT

Form:
<object height="50%" width="50%"
classid="clsid:22D6F312-B0F6-11D0-94AB-0080C74C7E95">
<param name="AutoStart" value="1" />
<param name="FileName" value="sample.wav" />
</object>

Here is an example:


The World Wide Web Consortium (W3C) recommends using the OBJECT element instead of EMBED. Yet I discuss the solution with EMBED here, because I couldn't create an OBJECT that was as user-friendly, cross-browser, cross-platform, less plug-in dependent, as the solution with EMBED.

  And The Winner Is ...

So far the streaming effect has not been discussed. All of the above mentioned media players are capable to start playing before the whole sound file is downloaded. However, the commonly used file formats, .wav, .mid, .mp3 don't tell the player to stream. Fortunately, the format m3u does. Unfortunately, browsers don't necessarily know, what to do with an m3u file, unlike, for example, with an .mp3 sound file or with a .gif image file. You may be as hasitant as the browsers, so, I let you know what m3u file is. M3U is a media queue format, also known as a playlist. In its simplest format it is a list of sound file names, separated with new lines. Here is an example:

Sample.mp3
music/Song.mp3
http://www.juancarlosproductions.com/music/mystaSample.mp3

The first line refers to a sound file being in the same folder as the m3u file, the second to one being in a music subfolder, and the third to a sound file on the Net. The form of first line is the shortest, but of the last line is the safest. Let's save a text file that contains the third line only, or a similar reference to a sound file, as sample.m3u, and invoke it from an EMBED tag:

<embed src="sample.m3u" type="application/x-mplayer2"></embed>

Interestingly, m3u has its dedicated MIME type, audio/x-mpegurl, but it doesn't always work. In default setting, Firefox for Windows doesn't recognize audio/mpegurl (or audio/x-mpegurl). An in-depth recent article on boutell.com suggests to refer to the m3u as "audio/mpeg" type. According to Thomas Boutell, this type calls the correct media player assigned to the m3u type files. In my experience, it doesn't work with the default settings of Opera in Win 2000 or in XP, but the type="application/x-mplayer2" does. In Windows XP the latter type correctly invokes the default media player of Windows from Firefox, too. I also experienced that the attribute autostart="0" of the EMBED tag works in more cases than the substantially equivalent autostart="false". My suggestion is to call the m3u play list in the following EMBED tag:

<embed src="sample.m3u" height="45" width="170"
    type="application/x-mplayer2" autostart="0"
    loop="0" volume="-300"></embed>

The above one-line HTML solution works with the default setup of IE6, Opera 7.21, FireFox 1.06 (Mozilla 5), Netscape 7.1 on Windows 2000 and XP; and sometimes with Safari on Mac OS. To make it always work with Mac/Safari and with Firefox on Linux and with other Mozilla versions in non-Windows platform, I created a Javascript. It checks and resets the MIME type of the embed tag to "audio/mpeg", if necessary. So far, I haven't heard back any problems with listening to the music on the following page. Open the sample page.

So, I am sharing the general solution with you. It is not too difficult, although requires some understanding of Javascript.

  General solution

To make pages context-sensitive, we need to add scripts to the HTML. The following solution doesn't require any special configuration of the Web server or of the client's computer. It doesn't contain long sniffing code for finding the platform and the browser version of the visitor's computer. With this Javascript we can check the available plugin and create an EMBED tag with proper MIME type.
Let's first put a SPAN in the HTML page, where we want the EMBED tag later:

<span id="sample">Finding plugin...</span>

Note that I'm using the m3u file's name as the span's id. The following function finds the SPAN with a given id and inserts the EMBED tag into the SPAN, by replacing the "Finding plugin..." text:

function setEmbed(ID, dir) {
    var element = document.getElementById(ID);
    //Write the following three lines in one:
    element.innerHTML = '<embed src="'+dir+ID+'.m3u"
      autostart="0" loop="0" height="45" width="170"
      type="'+getMimeType()+'"></embed>';
}// end function setEmbed

The getElementById function works in all modern browsers. If you want to take care of the less up-to-date visitors, read the One Code Fits All article. The setEmbed function calls the getMimeType function, which returns the proper MIME type:

function getMimeType(){
var mimeType = "application/x-mplayer2"; //default
var agt=navigator.userAgent.toLowerCase();
if (navigator.mimeTypes && agt.indexOf("windows")==-1) {
//non-IE, no-Windows
  var plugin=navigator.mimeTypes["audio/mpeg"].enabledPlugin;
  if (plugin) mimeType="audio/mpeg" //Mac/Safari & Linux/FFox
}//end no-Windows
return mimeType
}//end function getMimeType

The navigator.mimeTypes object returns false in Internet Explorer, and the second condition makes sure that the platform is not Windows. The setting to default MIME type doesn't need changes in any browsers running on Windows 2000/XP or in IE on any platform. Obviously, this function can be refined and extended, if one wants to consider more situations, more MIME types. I, for one, haven't checked any Unix setup yet but some of my readers have. For example, a Unix machine with Firefox and installed mplayer plug-in played the embedded play list flawlessly.

The above two functions should be placed in the HEAD section between a

<script language="JavaScript" type="text/javascript"> and a
</script>.

The best place and time to invoke the setEmbed function is in the BODY tag after page load:

<body onload=
  "setEmbed('sample', 'http://www.yourdomain.com/music/')">

The above code replaces the "Finding plugin..." text with the media player's control buttons after the page has been loaded and the proper player has been found. Then a little extra time is needed to load and buffer the beginning of the sound. During these few seconds the Play button looks grey, i.e., disabled. Clicking on the later enabled Play button, it will immediately start playing the sound file listed in the sample.m3u play list, which resides in the music subdirectory of yourdomain.com.

  Summary

A simple HTML solution has been suggested for playing audio. This solution covers at least 90% of the users; those who use almost any browsers in Windows 2000 or XP. By adding a dozen lines of Javascript we can also reach the growing camp of users, who utilise other configurations, like Firefox in Unix/Linux or Safari in Mac OS.


Read more articles on Web design and development.