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:


<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

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

Levers

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

20 most recent responses (oldest first):

07-Sep-11 06:27
Hi Matt.

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
12-Sep-11 05:13
@Hoelscher: Yes I get the same error (in English of course!) on your page when using IE9 in IE7/8 mode.

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.
12-Sep-11 05:54
Hi Matt

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
15-Sep-11 02:25
Hi 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?
29-Sep-11 12:32
Hi Folks -
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?
30-Sep-11 01:47
@ Marci: Once the user leaves the page? No - unless you open the page containing the audio element in a separate window, or store it in a frame within a frameset. The same is true of Flash.
07-Oct-11 04:52
The codes worked great . . thank you so much for sharing. We really wanted to have some background music playing on our main web page but wanted people to have the option to "stop" it as well.

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]
10-Oct-11 06:04
@stuseattle: Yep, that should do the trick
17-Oct-11 16:25
I am a novice, so forgive me if this is too much to ask. But is there anyway that you can use this code but with your own button? For instance an image of the little speaker icon instead of the buttons that are picture here...?

http://www.elated.com/res/File/articles/authoring/html/html5-audio/javascript-control.html
19-Oct-11 04:55
@lifeofbirds: Sure - just replace:


<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...
24-Feb-13 00:46
Sweet as ....
24-Dec-13 22:50
All the examples i see has a set path for the source.
Source =folder/christmas.mp3.....
I need the path to be a string
Like
String= what ever the user chooses.
Source ¥¥=string.

Any help on the syntax?
25-Dec-13 11:22
document.getElementByid('audio_element_id').src = ...


Bearing in mind that javascript cannot be used to search the user's local harddrive OR the server for the file to play, so you will have to create an array of existing media files to select from, or provide a means for the user to upload media.
25-Dec-13 11:26
I have a QR scanner that will call on the PHP page.
Depending on what the QR scanner submits to the PHP I wanted to select different audio sources.

Which will be sitting on the server.
Is the source needs to come from a string or a php get statement
Any sugestions ?
25-Dec-13 11:35
Any PHP code is over and done with before the browser even gets document source to start rendering it. So the PHP code has to set the element source attribute to the required value.
01-Mar-14 18:57
Matt:

I'm having problems with IE8 on XP. Your demo page loads with an error at Line 40, Character 66:

Object doesn't support this property or method.

Examining your source code, L40/C66 is the first "o" in:

"document.getElementById('myTuneObj').play()"

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.

When I display your demo page, the audio object is displayed as a very skinny box with what appears to be an orange "i" inside. None of the button controls work.

As a noob at media stuff, I've noticed a couple of things about your code that may or may not be significant.

1. In the <object> declaration, I see 'type="audio/x-mpeg". In other references, I've seen the type listed as "mpeg". Is the "x-" prefix correct?

2. In the button declarations, the ID used is 'myTune' while in the script the ID used is 'myTuneObj'. I'm assuming that, like CSS, the script overwrites the assignments to the buttons such that they point to the <object> instead of the <audio>. Is that correct?

3. Is there any software that must be loaded on the XP machine to respond to the creation of the <object>?

4. Are there any Windows security setting concerns? (I've seen some stuff on the 'net suggesting that might be an issue.)

Searching the 'net for other solutions turns up some pretty heavyweight stuff using various JS libraries. I like your lightweight solution, but have no idea how to fix it. I'm hoping that you already know the answer.

Thanks in advance for your assistance with this issue. If you don't have an XP machine on which to test, I'll happily run test cases for you on mine.

Greg
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">
</audio>

<!--<![endif]-->

<!--[if lt IE 9]>

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

<![endif]-->

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.

Greg
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! http://tocsin-bang.info

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

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