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

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.
30-Oct-15 12:50
Hey was wondering if you could do the same with getting the some album art when the song changes or cover for the each track
31-Oct-15 08:38
Only if you already had the image URI coded into the script and rewrote the code to change the src attribute of an image element at the same time as it changed the audio track.

But that addition is for you to experiment with, this article is for you to learn how to embed and play audio files using HTML5. It is not a fully operational "web media player" that you can just 'plugin' to a web document.
04-Nov-15 14:48
Hello. I can not figure out why the audio controls are working fine for Chrome, Safari, & Firefox, but will not work on Internet Explorer. I am getting the following message: "Error: Unsupported audio type or invalid file path." I have verified that all of the files are in the correct folder, named correctly, and all of them play fine.

Here is the code:
<audio controls>
<source src="" type="audio/mp3">
<source src="" type="audio/acc">
<source src="" type="audio/ogg">
Your browser does not support the audio element.

Here is the live page that the code is located on:

I am at a loss and would appreciate any help. Thank you in advance.
04-Nov-15 17:44
@zerojjc: Your MP3 URL returns a 404 error.
05-Nov-15 08:38
Thank you for your response. It is so strange, the files are there in the same folder/path. The only difference between them is the file type. I can not understand why these paths are exactly the same but the browser can not find the files that end with .mp3 in that folder.
05-Nov-15 08:42
I dont know if this helps, but here is a screenshot showing that all of these files are in the correct folder:
05-Nov-15 09:20

In FTP I decided to click “get info” on the .mp3 file and discovered the privileges for Group and World were not set to Read. I still have no idea why they were set properly for the .acc and .ogg files, but whatever I figured it out and now its working.

View all 45 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