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.

The Joy of HTML5 Audio: Tips & Tricks for Easy Sound Embedding

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.

To do this, you can add multiple <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:

  <source src="WhiteChristmas.mp3">
  <source src="WhiteChristmas.ogg">

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">

Adding player controls

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">

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">

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:

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.
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.
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">

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:

Start playback at the current playback position
Pause playback if the sound is currently playing
Determine if the browser can play a particular media type or not
The length of the sound clip, in seconds
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">

  <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>

  <audio id="myTune" controls>
    <source src="WhiteChristmas.mp3">
    <source src="WhiteChristmas.ogg">

<!--[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" />

    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() };



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.


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

20 most recent responses (oldest first):

02-Mar-14 09:07
"which seems like an odd place for the parser to have detected the error, but that's Character 66 assuming that the first column of the line is 1."

That's not where the error IS, just where it occurred when the interpreter tried to execute code and couldn't.

The actual error will be earlier in the source code not where it is reported.

However IE8 does NOT and never will support HTML5 audio, IE9 was the first version to do so.
02-Mar-14 11:59
After considering the fact that IE7/8 will be in use less and less, especially with the EOL of XP, I've decided to side step the issue of providing a player on my web page for those users.

Instead, I offer the following solution which simply requires that those users download the sound file and play it in their MP3 player.

<!--[if gte IE 9]><!-->

<audio controls preload="auto">
<source src="media/hear_me.mp3" type="audio/mpeg">
<source src="media/hear_me.ogg" type="audio/ogg">


<!--[if lt IE 9]>

<a href="media/hear_me.mp3">Click to download my message.</a>


The conditional comments around the <audio> section are treated as simple comments by all browsers other than IE, so those browsers provide a player to the user. And IE 9+ does the same.

For IE 7/8, the second conditional comment surrounds a link to the MP3 file so that those users can download the file.

For the purposes of my web page and my user set, I decided that this was the right balance of usability and my development time since most of my users probably aren't using IE 7/8 even now, and launching an external player does not strike me as a problem. YMMV.

08-Apr-14 06:36
I've been trying for weeks to get audio to play on the homepage of my site, for mood setting purposes. I'd tried dozens of approaches recommended by other sites, and none of them worked. This morning I came across your site and method, and fifteen minutes later its working fine in IE and Firefox, but not in Chrome (not too worried I hate Chrome with a vengeance). That time included converting the file from .wav to .mp3 and .ogg and uploading the new homepage and the audio files. BRILLIANT!

[Edited by tocsin on 08-Apr-14 06:38]
08-Apr-14 14:47
Found the problem and it had nothing to do with the html! Its just a problem with Chrome, I've used a workaround that wouldn't suit everyone. By default my soundcard settings in W8 are for 5.1, just changed it to 2.1 and everything is fine.
05-May-14 11:18
You use three buttons. I understand how to use my own buttons in place of these, but is it also possible to combine the play and pause functions into a single button?
05-May-14 13:01
05-May-14 13:20
Ah, good.

05-May-14 15:07
Toggle the button's function depending on it's state when clicked.

It's exactly the same as the hundreds of show/hide functions that are in use.
06-May-14 03:56

Pity you don't know how to do it yourself, otherwise you could have provided an example. Still, I shall see what I can find.
06-May-14 10:57
Oh I do, that's how I am able to tell you exactly what you need to find out.

Learning it for yourself will teach you FAR more than me simply "spoon-feeding" you an instant solution in working code.
25-Jun-14 08:52
Very useful and smart solution. It saved my day actually because I was strugling to control the play/pause elements using javascript and having lot of conflicts with my existing javascript plugins on my website.

A five star to you man. Keep up the good work.

16-Apr-15 01:09

I am an ABSOLUTE beginner at this, Ive read through some text books and other sites and your explanation seems to be the most simple.

Ive copied the instructions, but still cant get any sound when I click my "OK" button.

<!DOCTYPE html>

<audio id="sound">
<source src="isi.BANNER/beep26.wav">

<button onclick="document.getElementById("sound").play()">OK</button>





What am I doing wrong?
16-Apr-15 05:59
Does the browser you are using support HTML5 Audio?
16-Apr-15 06:02

is the wave file in the same folder on the server as the HTML document and is it spelled EXACTLY the same, including capitalisation?
16-Apr-15 09:24
Actually I havent put the wave file on the server yet, the path is from an internal folder on my computer. My next step is to put it on the server and make it external ( that the right word..?).

I figured it out, I just separated java script and html5 instead of <button onclick=getElement.....>, added this function to java script.

Thanks anyways:)
14-May-15 03:36
You are an idiot, I'll just keep on deleting your spammy crap and I assure you that;

YOU WILL get bored before I do.

[Edited by chrishirst on 14-May-15 16:32]
14-May-15 19:58
Excuse me? That wasnt a spammy crap message. I was genuinely asking how to write some codes.
15-May-15 05:57
No not you, ... the spamming idiot (roteiro) who's post I edited.

But for genuine questions please start a new thread rather than reuse a thread that is five years old and is actually for discussing a specific article. Make reference to the article certainly, but necroposting (posting in a long dead thread) only raises suspicion of your motives.
15-May-15 06:12
Thanks, I emailed elated asking how to start a new thread but received no reply.

My bad, for not realising this thread was 5 years old. Can you please tell me how to start my own discussion for the future?
15-May-15 07:25
>>" I emailed elated asking how to start a new thread but received no reply. "

You should read this.

>>"please tell me how to start my own discussion for the future?"

At the top of every forum category ( for example), there is a link for "Post new topic". that will start a new thread in that section.
If you want a quicker response, give me a topic 'bump' (chris [at] webmaster-talk [dot] eu) and I'll see what I can do.

View all 38 responses »

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.

Top of Page