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
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!
Hoelscher says
Hi there,
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
matt says
@Hoelscher: Hmm, it works fine for me when using IE9 in IE7/8 mode. The browser asks if it’s OK to use the Windows Media Player plugin – when you agree then the embedded player appears, and you can start playing by clicking the Play Music button.
Could it be that your particular IE doen’t have the plugin installed, or it’s being blocked by the browser’s security settings?
Hoelscher says
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
matt says
@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.
Hoelscher says
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
matt says
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?
MarciCurtis says
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?
matt says
@ 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.
stuseattle says
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]
matt says
@stuseattle: Yep, that should do the trick 🙂
lifeofbirds says
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
matt says
@lifeofbirds: Sure – just replace:
with something like this:
etc…
Robin Thebs says
Sweet as ….
Triley says
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?
chrishirst says
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.
Triley says
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 ?
chrishirst says
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.
GregoryRHill says
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
chrishirst says
“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.
GregoryRHill says
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
tocsin says
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]
tocsin says
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.
dneale says
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?
chrishirst says
Yes.
dneale says
Ah, good.
How?
chrishirst says
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.
dneale says
Thanks.
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.
chrishirst says
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.
designchef says
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.
Thanks
jj24 says
Hi,
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>
<html>
<head>
<audio id=”sound”>
<source src=”isi.BANNER/beep26.wav”>
</audio>
<button onclick=”document.getElementById(“sound”).play()”>OK</button>
</head>
<body>
</body>
</html>
What am I doing wrong?
Thanks.
chrishirst says
Does the browser you are using support HTML5 Audio?
chrishirst says
AND,
is the wave file in the same folder on the server as the HTML document and is it spelled EXACTLY the same, including capitalisation?
jj24 says
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 (…is 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:)
roteiro says
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]
jj24 says
Excuse me? That wasnt a spammy crap message. I was genuinely asking how to write some codes.
chrishirst says
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.
jj24 says
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?
chrishirst says
>>” I emailed elated asking how to start a new thread but received no reply. ”
You should read this.
http://www.elated.com/articles/the-future-of-elated/
>>”please tell me how to start my own discussion for the future?”
At the top of every forum category (http://www.elated.com/forums/authoring-and-programming/ 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.
NNoBoDY says
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
chrishirst says
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.
zerojjc says
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=”http://creationkidz.com/wp-content/themes/3RF-site/music/sample-page-33.mp3″ type=”audio/mp3″>
<source src=”http://creationkidz.com/wp-content/themes/3RF-site/music/sample-page-33.aac” type=”audio/acc”>
<source src=”http://creationkidz.com/wp-content/themes/3RF-site/music/sample-page-33.ogg” type=”audio/ogg”>
Your browser does not support the audio element.
</audio>
Here is the live page that the code is located on: http://creationkidz.com/sample-page-four/
I am at a loss and would appreciate any help. Thank you in advance.
matt says
@zerojjc: Your MP3 URL returns a 404 error.
zerojjc says
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.
zerojjc says
I dont know if this helps, but here is a screenshot showing that all of these files are in the correct folder: http://imgur.com/78dXQMT
zerojjc says
I FIGURED IT OUT!
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.
JKorsten says
Hey,
I really like this post, it’s really clear and to the point.
I’m also trying to add a player on a webpage but it doesn’t work for me.
What I try to do is to play a wav file.
This works fine for Chrom and FireFox, but for IE it doesn’t work. I’m using IE11.
I’ve also checked other websites and one website mentions IE doesn’t support .wav files.
http://www.w3schools.com/html/html5_audio.asp
Your post mentions that IE supports .wav so now I’m a bit confused.
Could you please help me because I also need the .wav files to be able to play in IE.
Kind regards,
JKorsten
PS: the code I’m using is:
chrishirst says
Internet Explorer only supports .wav format when using the IE proprietary bgsound element which is autoplay only.
https://www.w3.org/wiki/HTML/Elements/bgsound
JKorsten says
Ok thanks for the quick reply.
Unfortunately that’s not what I want.
I also tried the embed tag which works fine on IE and FF but this has troubles on Chrome where it ignores the autoplay/autostart tag (which is put to false). So everytime I start the page in chrome it starts playing (which I don’t want).
So there isn’t a way to make the playing of wav’s work on IE, FF and Chrome?
chrishirst says
As there is no one single way that it can be made to work in all browsers, you will have have to go through a
try { … } catch { … } finally … (http://www.w3schools.com/jsref/jsref_try_catch.asp)
process to identify what works in each browser and deliver the appropriate code to that particular user agent.
It used to be known as “Browser sniffing” in the “bad old days”.
So welcome to the wonderful world of browser programming.
amansh29894 says
there is another way to play sound by using javascript i found a complete and good tutorial on http://www.talkerscode.com
and it is with demo also
http://talkerscode.com/webtricks/play-sound-on-notification-using-javascript-and-php.php
Timy says
Hi Matt!
I wonder if “click to play” is possible by using HTML ONLY and without using javascript?
https://www.elated.com/res/File/articles/authoring/html/html5-audio/javascript-control.html
Actually I want to do the same in an ePub ebook.
Thanks for any kind of help!
Timy
Matt Doyle says
Sure, just use the audio element with the
controls
attribute.igre says
really clear and to the point. nice job Matt
Glenda says
I see a bunch of comments about having background music auto playing for users. just wondering if anyone considered visually impaired users that won’t be able to hear their screen reader because of background sounds?