The Joy of HTML5 Audio: Tips & Tricks for Easy Sound Embedding
Learn how to use the HTML audio element to embed sounds in your web pages easily. Lots of code examples are included in the tutorial.
Up to now, playing audio in a web browser has been a bit of a black art. Traditionally there are several ways to embed a sound in a web page — some work better than others, and many only work if you happen to be using the right browser with the right plugin.
The ubiquity of the Flash plugin has helped to a large extent, since Flash makes it easy to embed audio in a way that works with most browsers. However, this doesn't help with browsers such as Safari on the iPhone and iPad, which don't support Flash at all.
In short, it's all a bit of a mess.
Fortunately, HTML5 looks set to make life easier for us developers, thanks to its audio element. This element lets you embed an audio file in a web page, as well as control playback of the sound using JavaScript. More importantly, it doesn't require any plugin to work, and is supported by nearly all modern web browsers. (We'll come back to browser support later!)
In this tutorial I'll show you how to embed sounds in a page with the audio element. We'll also take a look at how to trigger and stop the audio via JavaScript, and how to ensure our audio can play on as many web browsers as possible.
The HTML5 audio element
The basic audio element is really easy to use. Since it's the season to be jolly — and Europe's getting more than its fair share of snow right now — let's embed a short MP3 snippet of Bing Crosby's "White Christmas":
<audio src="WhiteChristmas.mp3"></audio>
Not much explanation needed here! Much like the <img> tag lets you include an image file in a page, the <audio> tag includes an audio file.
Cross-browser support
Simple though the above example is, it won't work in many browsers. This is down to audio file formats.
Some browsers can play .mp3 files but not .ogg files, while other browsers can play .ogg files but not .mp3. Most browsers can play .wav files, but WAVs are uncompressed, resulting in large file sizes which are impractical for anything other than short audio snippets.
Here's a summary of current browser support for various audio formats:
| Browser | .mp3 |
.ogg |
.wav |
|---|---|---|---|
| Firefox 4 | No | Yes | Yes |
| Safari 5 | Yes | No | Yes |
| Chrome 8 | Yes | Yes | Yes |
| Opera 11 | No | Yes | Yes |
| IE9 | Yes | No | Yes |
What audio formats does your browser support? Find out with this handy test page.
As you can see from the table, the only practical way to provide cross-browser support for audio playback is to serve .mp3 files to those browsers that can play them, and .ogg files to the others.
<source> elements to the <audio> element to specify the same sound file in multiple formats. The browser will then play the first file that it's capable of playing. Here's an example:
<audio>
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
Of course, this does mean that you need to create both .mp3 and .ogg versions of your sound file (tools such as Audacity are handy for this), but it will give you good cross-browser support.
Older versions of Internet Explorer — that is, versions 7 and 8 — don't even support the audio element. However, we'll look at how to support these browsers later in the article.
Playing a sound automatically
While the above code embeds a sound file, it doesn't actually play it, so it's not much use on its own. If we want the sound to play automatically when the page has loaded, then we can add an autoplay attribute to the element:
<audio autoplay>
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
Adding player controls

While autoplay can be useful at times, it can also be annoying to have sounds or music start playing as soon as you view a page. A nicer approach is to add controls to the audio element so that the user can start and stop the audio themselves:
<audio controls>
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
Typically, this adds a horizontal control bar featuring a play/pause button, a timeline with draggable playhead, and a volume control, much like you see at the bottom of a YouTube video.
It's worth bearing in mind that the controls will look — and sometimes behave — differently in each browser. For example, there's no volume control on an iPhone, since the user can just use the hardware volume buttons.
Looping playback
Adding the loop attribute to the <audio> tag causes the audio to play endlessly:
<audio loop>
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
This can be useful for things like background music and sound effects in games.
Preload hinting
You can optionally use the preload attribute to give the browser a hint as to whether, and how, it should preload the audio file when the page loads. Preloading the audio file means it can play instantly when the user hits the "play" button, which is a nicer experience for the user.
Values for this attribute are:
none- The browser shouldn't bother preloading the audio file. Use this setting when you don't expect the audio to be played by most users, or when you want to conserve your server bandwidth as much as possible.
metadata- This is similar to
none, except that you're telling the browser it's OK to load the audio file's metadata, such as its duration. Still, the browser should not preload the actual audio data. auto- It's OK for the browser to preload the entire audio file, if it wants to.
For example:
<audio preload="metadata">
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
Bear in mind that preload is just a hint. The browser can choose to ignore it and do what it wants!
Controlling playback with JavaScript

One of the nice things about HTML5 audio elements is that they're easy to control using JavaScript. The audio element provides many useful properties and methods — here are just a few:
play()- Start playback at the current playback position
pause()- Pause playback if the sound is currently playing
canPlayType(type)- Determine if the browser can play a particular media type or not
duration- The length of the sound clip, in seconds
currentTime- The current playback position, in seconds. You can also set this property to move the playback position.
Using some of the above properties and methods, we can create some rudimentary buttons to play, pause, and stop our music:
<audio id="myTune">
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
<button onclick="document.getElementById('myTune').play()">Play Music</button>
<button onclick="document.getElementById('myTune').pause()">Pause Music</button>
<button onclick="document.getElementById('myTune').pause(); document.getElementById('myTune').currentTime = 0;">Stop Music</button>
Supporting older versions of Internet Explorer
So far we've assumed that our user's browser supports the HTML5 audio element. Sadly, Internet Explorer 7 and 8 don't! (IE9 does, thankfully.) It would be nice to provide some sort of fallback for those users who are using IE7 or IE8.
A crude but effective way to do this is to use conditional comments to single out these browsers, and present them with an object element pointing to the sound file. The browser then usually displays an embedded controller, allowing the user to play, pause and rewind the music much like the HTML5 controller. Here's an example:
<div id="content">
<div style="margin-bottom: 20px;">
<button id="playButton" onclick="document.getElementById('myTune').play()">Play Music</button>
<button id="pauseButton" onclick="document.getElementById('myTune').pause()">Pause Music</button>
<button id="stopButton" onclick="document.getElementById('myTune').pause(); document.getElementById('myTune').currentTime = 0;">Stop Music</button>
</div>
<audio id="myTune" controls>
<source src="WhiteChristmas.mp3">
<source src="WhiteChristmas.ogg">
</audio>
<!--[if lt IE 9]>
<object id="myTuneObj" type="audio/x-mpeg" data="WhiteChristmas.mp3" autoplay="false" height="45">
<param name="src" value="WhiteChristmas.mp3" />
<param name="controller" value="true" />
<param name="autoplay" value="false" />
<param name="autostart" value="0" />
</object>
<script>
document.getElementById('playButton').onclick = function() { document.getElementById('myTuneObj').play() };
document.getElementById('pauseButton').onclick = function() { document.getElementById('myTuneObj').pause() };
document.getElementById('stopButton').onclick = function() { document.getElementById('myTuneObj').stop() };
</script>
<![endif]-->
</div>
The above example will work on all browsers that support HTML5 audio, and fall back to the object approach for IE7 and 8. Within the conditional comments, I've also remapped the click event handlers for the Play/Pause/Stop buttons so that they can control the audio object in IE7/8 (which, handily, provides play(), pause() and stop() methods).
Another approach is to fall back to a Flash audio player for IE7/8. Here's a good post that shows how to use the audio element with a free Flash player fallback.
Summary
In this tutorial you've seen just how easy it is to embed and play back audio files using HTML5. Not only is the audio element simple to use, it's also very customizable, plus you can easily control playback through JavaScript.
Want to find out more about HTML5 audio, and what it can do? Check the spec.
Although support is lacking in some browsers, such as older versions of Internet Explorer, it's perfectly possible to start using HTML5 audio — with fallbacks, if necessary — today.
I hope you enjoyed this tutorial, and Merry Christmas to you!
Follow Elated
Related articles
Responses to this article
13 responses (oldest first):
I've followed your tutorial and got the sounds running easily. Only the fallback won't work. I'm using IE8, and so it's supposed to work, since the condional addresses "lt IE9". When I look at your site with IE8 the same happens, so I couldn't have done something wrong. I would love to get it running. Maybe you have an idea?
This the error message in IE8:
"Details zum Fehler auf der Webseite
Benutzer-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; Mozilla/4.0 (compatible; MSIE 7.0; Win32; 1&1); GTB7.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Zeitstempel: Mon, 5 Sep 2011 12:54:07 UTC
Meldung: Das Objekt unterstützt diese Eigenschaft oder Methode nicht.
Zeile: 40
Zeichen: 66
Code: 0
URI: http://www.elated.com/res/File/articles/authoring/html/html5-audio/all-browsers.html
Meldung: Das Objekt unterstützt diese Eigenschaft oder Methode nicht.
Zeile: 41
Zeichen: 67
Code: 0
URI: http://www.elated.com/res/File/articles/authoring/html/html5-audio/all-browsers.html"
Thanks in advance
Peter
Could it be that your particular IE doen't have the plugin installed, or it's being blocked by the browser's security settings?
Thans for your reply. I've tested the page in other IE9, with the IE8 emulation on, but always the same; I get this error message, the the object doesn't support this method, whatever thies means. You can have a look at my construction here: http://www.umbra.de/akademie/#section-2. In my IE8 it looks like this screenshot: http://www.umbra.de/IE8-mode.gif
I didn#t find any possibility to tweak the security options, so that it worked; maybe you can point me in the right direction?
Thanks again
Peter
I looked at your page source and I can't see the fallback code there at all (i.e. the code in the "Supporting older versions of Internet Explorer" section at http://www.elated.com/articles/html5-audio/ ). So this is presumably why it's giving the error.
Add the fallback code to your page and it should then work.
Sure the code isn't on my site anymore, I've been working on it recently to present it to my client. But it's much easier: In my IEs your fallback code also doesn't work: http://www.elated.com/res/File/articles/authoring/html/html5-audio/javascript-control.html. I've tried it with IE9 in IE8 mode and with a native IE8, the result is the error message in both cases.
Thank you for your effort. I have no idea, what can be wrong ...
Best regards
Peter
That is strange. As I say, my fallback code works fine in my IE9, in all modes!
Anyone else seeing any problems with the IE7/8 fallback code?
I'm wondering if HTML5 will let me post an audio file that will continue to play once people click to other pages. Is there any way to do this in Html without flash?
I was wondering if there's a way that a single button could control pause and resume? For example, we have the music autoloading when you hit the page; the "pause" button stops the music buy we'd love it if hitting that same "pause" button would restart.
Anyone know if that's possible?
stu
WAIT - Found the answer and thought I'd share it with you.
After the audio code, paste:
<button type="button" onclick="aud_play_pause()">Play/Pause</button>
<script>
function aud_play_pause() {
var myAudio = document.getElementById("myTune");
if (myAudio.paused) {
myAudio.play();
} else {
myAudio.pause();
}
}
</script>
[Edited by stuseattle on 07-Oct-11 05:01]
http://www.elated.com/res/File/articles/authoring/html/html5-audio/javascript-control.html
<button onclick="document.getElementById('myTune').play()">Play Music</button>
with something like this:
<img onclick="document.getElementById('myTune').play()" src="mybutton.png" alt="Speaker icon" title="Play Music">
etc...
Post a response
Want to add a comment, or ask a question about this article? Post a response.
To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.
