Unlocking the power of HTML5 <audio>

Sounds form the background of our life. Today the HTML5 <audio> element enables Web developers to embed sounds in their applications. The flexibility of the control coupled with the integration with the rest of the platform allows several scenarios, from simple sound effects to background audio to gaming experiences to more sophisticated audio engines.

This blog post walks through some of the best practices for using the <audio> tag in your Web applications, and includes useful tips from real-world sites.

Adding an audio element to your page

The very first step is to add the audio element to your page. You can do this by declaring an <audio> tag in your markup, by instantiating a new audio element in the JavaScript code, or by embedding the audio stream in the page:

<audio src=”audio/sample.mp3″ autoplay>


Run live demo

var audio = document.createElement(“audio”);

if (audio != null && audio.canPlayType && audio.canPlayType(“audio/mpeg”))


audio.src = “audio/sample.mp3”;



Run live demo

<audio src=”data:audio/mpeg,ID3%02%00%00%00%00%…” autoplay>


Run live demo

The first approach allows you to initialize the audio components during the page load. The second approach gives you more flexibility and better management of the network flow, as it defers the loading of the audio clip to a specific time during the application lifecycle. The third approach (less recommended) consists in embedding the audio files as data-uri in the page, reducing the number of requests to the server.

Note that you can play an audio element generated by JavaScript even if it’s not been actually added to the DOM tree (like in the code snippet above). However adding the audio element to the page will allow you to display the default control bar.

HTML5 Audio Controls

Although not covered in this post, you can support more than one audio file format. Also, if you are hosting the audio files on your server, remember to register the MIME type for mp3 files (“audio/mpeg”) on the server side. Here, for instance, is the setting on Internet Information Services (IIS).

HTML5 Audio Mime Type

Preloading the audio before playing

Once you have your audio element, you can choose the best preloading strategy. The HTML5 <audio> specification describes a preload property with three possible values:

  • “none”: hints to the user agent that either the author does not expect the user to need the media resource, or that the server wants to minimize unnecessary traffic.
    If your scenario is a podcast blog with an audio file for each post, this option works particularly well, as it reduce the initial preload bandwidth. Once the user plays the file (either through the default visual controls or the JavaScript methods load() or play()), the browser will start fetching the audio stream.
  • “metadata”: hints to the user agent that the author does not expect the user to need the media resource, but that fetching the resource metadata (dimensions, duration, etc.) is reasonable.
    This option is recommended if you are building an audio player control and you need basic information about the audio clip, but don’t need to play it yet.
  • “auto”: hints to the user agent that the user agent can put the user’s needs first without risk to the server, up to and including optimistically downloading the entire resource.
    If you are building a game, this approach is probably the best one, as it allows you to preload all the audio clips before actually starting the game experience.

Note that when you set the src property of the audio element programmatically, the browser will set the preload property – unless otherwise specified – to “auto.” For this reason, if your scenario needs a different value, make sure to specify it in a line of code before setting the src.

You can preview the impact over the network of these three options by running this page using the F12 Developer Tools (Network Tab). For debug purposes, you can simulate new calls and disable the local cache by checking the “Always refresh from sever” menu.

Disabling cache with F12 Tools


Network with preload none


Network with preload metadata


Network with preload auto

While this property is great for the initialization phase, you might also need to know when the browser actually downloaded the audio clip and is ready to play it. You can get this information by listening to the “canplaythrough” event; this event is called by the User Agent once it estimates that if playback were to be started now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering.

var audio = document.createElement(“audio”);

audio.src = “audio/sample.mp3”;

audio.addEventListener(“canplaythrough”, function () {

alert(‘The file is loaded and ready to play!’);

}, false);

Run live demo


Another frequent request for scenarios with audio is the ability to loop a sound clip. With the HTML5 <audio>, you can do this using the “loop” property; this setting will loop your clip forever, or until the user or the application activates the pause() audio control.

<audio src=”audio/sample.mp3″ autoplay loop>


Run live demo

Another approach to loop an audio file is to programmatically call the play() method when the audio clip ends; doing so will allow you eventually to manage the delay between one loop and the other.

var audio = document.createElement(“audio”);

audio.src = “piano/3C.mp3”;

audio.addEventListener(‘ended’, function () {

// Wait 500 milliseconds before next loop

setTimeout(function () { audio.play(); }, 500);

}, false);


Run live demo

Note that any play() call executed on the audio element before the sound actually ended won’t have any effect. If you are interested to “cancel and restart” the current sound, you will need to reset the currentTime.

var audio = null;

audio = document.createElement(“audio”);

audio.src = “piano/3C.mp3”;

audio.addEventListener(‘ended’, function () {


}, false);

function play() {



function restart() {

audio.currentTime = 0;



Run live demo

Multiple audio tags

If your scenario needs the same audio file to be played several times concurrently (that is, with overlapping sounds), you can achieve this result by creating multiple audio tags pointing to the same file. Obviously the same approach also works if you are using different audio files at the same time. As we explained earlier in this post, you can either add those programmatically or by instantiating them in the markup.

The following code snippet shows how to load and play multiple audio files using markup. The audio samples all have the same length; at the end of the execution, they will loop starting from the beginning. As you play them in Internet Explorer 9, you can notice that they are automatically synchronized throughout various loops. You will notice that the combination of these 5 sounds will play like the audio file used in the previous demo (“sample.mp3”).


<audio src=”audio/Bass.mp3″ autoplay loop>


<audio src=”audio/Drum.mp3″ autoplay loop>


<audio src=”audio/Crunch.mp3″ autoplay loop>


<audio src=”audio/Guitar.mp3″ autoplay loop>


<audio src=”audio/Pizzicato.mp3″ autoplay loop>



Run live demo

While this approach is very simple and straightforward, in most scenarios developers prefer to create the audio clips programmatically. The following code snippet shows how to add 3 audio clips dynamically using code. As you play them together, you will get the C Major chord!




function AddNote(name) {

var audio = document.createElement(“audio”);

audio.src = “piano/” + name + “.mp3”;

audio.autoplay = true;


Run live demo

This code pattern works on any browser and will allow you to build very compelling scenarios!

It’s important to keep in mind that as your application or game becomes more complex you might eventually reach two limits: the number of audio elements you can preload on the same page and the number of audio elements you can play at the same time.

These numbers depend on the browser and the capabilities of your PC. Based on my experience, Internet Explorer 9 can handle dozens of concurrent audio elements simultaneously with no issues. Other browsers don’t do as well – you might encounter evident delays and distortions as you play multiple files in a loop.

Synchronization strategies

Depending on the characteristics of the network, you should always consider the delay involved between adding the tag, getting the content and being ready to play it. In particular, when you are handling multiple files, each file might be ready to play earlier or later. Here, for instance, is a capture with the 3 files used previously, loaded from the local host.

Audio synchronization

As you can see in the Timings column, different files might be ready at a different time.

A very common synchronization strategy is to preload all the files first. Once they are all ready, you can quickly iterate through a loop and start playing them.

var audios = [];

var loading = 0;








function AddNote(name) {


var audio = document.createElement(“audio”);

audio.loop = true;

audio.addEventListener(“canplaythrough”, function () {


if (loading == 0) // All files are preloaded


}, false);

audio.src = “piano/” + name + “.mp3”;



function StartPlayingAll() {

for (var i = 0; i < audios.length; i++)



Run live demo

Let’s bring everything together now! The following demo simulates a piano playing Frère Jacques (also known as Brother John, Brother Peter…or Fra Martino). The page starts fetching all the notes, showing the progress as they get preloaded on the client. Once they are all ready, the song starts and keeps playing in a loop.

Fra Martino

Run live demo

Audio in real world sites

Now that we’ve seen the common patterns to handle multiple audio files, I’d like to highlight a few Web sites as examples of best practice uses of the <audio> tag.

Pirates Love Daises: www.pirateslovedaisies.com

In another blog post I talked about Pirates Love Daises, an awesome HTML5 game built by Grant Skinner. In addition to great game play and compelling visual effects, Grant’s team also developed a sophisticated audio library that plays several audio samples throughout the game. The main logic is encapsulated within the AudioManager class. As suggested earlier, before actually starting the game the site preloads all the audio clips and display the cumulative progress in the initial loading screen. The site takes also into consideration the case of network timeouts or errors occurred while downloading an audio file.

Pirates Love Daisies


var h=document.createElement(“audio”);





















trace(“Error Loading Audio:”,b.target.id);






trace(“Audio Timed Out:”,this.currAsset.id);




Run live demo

Grant is currently working on a Sound Library project that will allow developers to use their sound engine’s logic with any other application. Looking forward to that!

Firework (by Mike Tompkins): www.beautyoftheweb.com/firework

The Firework demo is particularly interesting, as it allow you to interact with several audio tracks at the same time, dynamically changing the volume of each track. Moreover, as you interact with the audio channels, the interface dynamically reacts to different inputs or settings.


This time the audio tags have been declared in the HTML markup (there are just 6 tracks). The progress is tracked programmatically by listening to the canplaythrough event. Once all audio files are ready to play, a loop goes through the list and starts playing.

video.addEventListener(‘canplaythrough’, onCanPlayAudio, false);

for (var i = 0; i < 5; i++) {

var aud = document.getElementById(“aud” + i);


aud.volume = 0;


“tag”: aud,

“ready”: false


aud.addEventListener(‘canplaythrough’, onCanPlayAudio, false);


// Set audio/video tracks

document.getElementById(“tompkins”).src = MediaHelper.GetVideoUrl(“Firework_3”);

for (var i = 0; i < audioTracks.length; i++) {

document.getElementById(“aud” + i).src = MediaHelper.GetAudioUrl(audioTracks[i]);


Run live demo

The developers in this case also made the decision to start with the volume set to 0 and to increase it dynamically to 1 as soon as the experience is ready to play. Depending on the quality of your audio card and drivers, this little trick reduces the likelihood of hearing an initial “knock” noise when the audio starts.

BeatKeep: www.beatkeep.net

The last scenario is probably the most complicated of the examples shown here. In this example, you can build your own songs using a beat machine and playing several audio clips in a loop. In this application, it’s critical to have perfect synchronization of the audio channels and an agile buffering system to load multiple clips.


The beat machine gives you full control over the tempo and the time signature; using sophisticated timer logic and binding model—the end result is a very smooth experience!


I encourage you to try all the samples and applications in this post using Internet Explorer 9 or other browsers and let us know what your experience was like! You can download all the sample code used in this article here.

If you want to learn more about the audio and video controls, I recommend that you watch the half-hour session from MIX “5 Things You Need To Know To Start Using <audio> and <video> Today” or read these interesting articles on the MSDN.

Thanks to DoubleDominant for the audio clips used in this blog post and to Grant Skinner and Archetype for their great HTML5 experiences.

—Giorgio Sardo | Sr. Technical Evangelist – HTML5 and Internet Explorer

Comments (48)

  1. alvatrus says:

    So, why doesn't this work?

      <audio src="sonate.mid" autoplay>


  2. Björn says:

    > addAudioChannel:function(b,a,f){,a,f){

    Something is wrong there.

  3. ieblog says:

    @alvatrus: What is the format of the sonate.mid file and what MIME type does the server send when serving it?

    @Björn: Thanks. Typo corrected.

  4. jabcreations says:

    The mp3 format is great though where is support for the Ogg Vorbis codec? As alvatrus points out why doesn't the audio element support the midi format? Interoperability automatically and inherently includes codecs in conjunction with the audio and video elements and IE9's implementation is NOT interoperable with other browsers nor is Safari.

  5. PhistucK says:

    As part of the example, you use "audio/mp3" as the MIME type –

    "if (audio != null && audio.canPlayType && audio.canPlayType("audio/mp3"))"

    But later you state "audio/mpeg" as the MIME type –

    "remember to register the MIME type for mp3 files (“audio/mpeg”)"

    Be consistent.

  6. nonlinearsound says:

    autoplay is not supported by mobile Safari currently!

    The playback needs to be triggered by the build in controls of the audio tagor a javascript function triggering the play() method after a user interaction.

  7. Aethec says:

    @JAB Creations: The ogg format is great though where is support for the MP3 codec? Interoperability automatically and inherently includes codecs in conjunction with the audio and video elements and Firefox's implementation is NOT interoperable with other browsers nor is Chrome.

    See? I can do it too!

  8. ieblog says:

    @PhistucK: I have updated the canPlayType call to use "audio/mpeg". I note, however, that browsers that can play MP3 files answer "maybe" to both canPlayType("audio/mpeg") and canPlayType("audio/mp3"). Browsers that cannot return "" to both calls.

    A test page for a collection of MIME types is at http://www.baccano.com/…/support.htm

  9. jabcreations says:

    @Aethec You should consider directing your concerns to relevant blogs.

  10. Andrew says:

    Why does IE continue to support royalty, patented and DRM encumbered formats such as MP3?

    OGG Vorbis fixes these issues as it does not have any DRM, is royalty free, and is a completely open standard.

    By the way, on my own websites I will only ever use Vorbis and other open standards for audio, never so-called "standards" that have these issues.

  11. johnnyq3 says:


    If Microsoft started to use it, they could get sued for some abritary thing that violates someones patent.  Then Microsoft might lose because they are an "evil" corporation.

  12. Klimax says:

    @Andrew: DRM on MP3? Good joke.

    You don't want to be taken seriously,do you?

  13. alvatrus says:

    Why does the following trigger a message in IE stating that scripts and ActiveX are restricted?

    <!DOCTYPE html>



         <audio src="django.mp3" autoplay>




  14. Paul says:

    There are some more examples of html audio (working) on puzzles / demos on various browsers at my homepage:


  15. Aethec says:

    @JAB Creations: It seems you didn't get my point, I'll make it clearer: Complaining because Browser X supports Format A but not Format B, which Browser Y support, is pointless.

    @Andrew: You do know that MP3 and WMA and all those format can also be used without DRMs, right?

  16. mike-mcgrath says:

    For cross-browser compatibility I suggest audio versions encoded in both MP3 and OGG be specified, like this:

    <audio controls>

    <!– Encoded for Internet Explorer, Google Chrome, and Safari –>

    <source src="audio.mp3" type="audio/mpeg">

    <!– Encoded for Firefox and Opera –>

    <source src="audio.ogg" type="audio/ogg">


    This example can be found at mike-mcgrath.net/…/audio.html and works in IE9, Firefox 4, Chrome 11, Safari 5,& Opera 11.

  17. yellowstone says:

    .jxr, .hdp  – Filename extension(JPEG XR) support!

  18. Andrew says:


    The fact remains, continuing support for MP3, AAC etc. allows big companies to use DRM. If MP3 is continued onto the web, it gives them the chance to drag DRM onto the web as well.

  19. Andrew says:


    That's the entire point of why software patents hold the web back. I suggest you read at http://endsoftpatents.org/

    I'm sure that if Microsoft really wanted to implement OGG, they would just do it. The big boys at Microsoft have plenty of money behind them anyway.

  20. Klimax says:

    @Andrew Incorrect. Mp3 has no drm. Was viewed as unsuitable by publishers due to that.(only few formats have builting support for drm)

    MS might have money but they have better use then being on recieving end of patent lawsuit. Like buying Skype…

  21. johnnyq3 says:


    Heres the thing if Microsoft tries to stop patenting stuff on their own then someone can swoop in and patent it.  RIM did the same thing to MS with Exchange related tech.  And now RIM tried to sue MS for Exchange related patents.

  22. Linr says:

    How to get ID3 info.Such as artist,lrc and so on?

  23. Andrew says:


    So according to you software patents are a problem but there's nothing we can do to stop it.

    In other words, we allow Microsoft to further infect the web with patented formats, and that's that.

    I mean sure, why not?

  24. Aethec says:

    @Andrew: They, just like many other companies, have no choice.

    Since that stupid patent system* is not going to disappear any time soon, they have to patent everything they can to avoid paying royalties to patent trolls such as Acacia Research.

    *I'm not saying patents are stupid ; the US patent system, however, is stupid.

  25. Fiery Kitsune says:

    I've been commenting on this blog since day 1 and I really don't appreciate it when the IE team makes "elephant in the room" blog posts.

    How can you guys talk about the audio tag and not explicitly mention Ogg?

    WebM. Ogg Vorbis. WebGL. Not scoring half of what other browsers score on HTML5Test. Are these things even on your radar?

    Are you going to let standard bureaucracy delay things another 3 or 4 years?

    You guys always dodge tough questions. I'd appreciate nebulous answers over silence.

  26. alvatrus says:


    Please give a reference in the HTML5 standard that stipulates that the formats WebM, Ogg Vorbis and WebGL must be included to meet that standard. Don't let yourself be misguided just because a few people say it's a good test because it trounces IE. The distribution of points in this test was specifically weighed to do that (in my not so humble opinion.)


    html5test is one of those "test"-sites that attempt to give a rating to standards support. The test itself just asks the browser "do you implement …?" If the browser responds "probably", or even "maybe" then that's another point in the bag. It doesn't test the implementation or the completeness of the feature. It also gives multiple points for the same feature. See WebM support both getting points in the audio and video section.

  27. Andrew says:


    The HTML5 standard originally recommended OGG (I believe) but changed it to allow any format. However MP3 and WMA aren't exactly open for any web browser to implement:

    WMA – a proprietry standard which contains DRM.

    MP3 – no DRM (I got confused with AAC) which is patented, but supposedly an "open" standard. Note that this format actually isn't open for anyone to implement.

    MP4/AAC – DRM and patents. Even worse than the above two formats.

    OGG Vorbis – an open standard, no DRM, no patents.

    HTML5 is supposed to be "open". Even though MP3 and WMA are "conforming" to the specification IE is still less open. So in my eyes, and in the eyes of many others (I'm sure), IE isn't truly conforming to HTML5 because it isn't using open standards.

  28. Spinoza says:

    Native MIDI support would be great for games!

  29. PatriotB says:

    <bgsound> still supports MIDI, AFAIK. 🙂

  30. Spinoza says:

    @PatriotB: But only through plugins, right?

    It's a shame as MIDI files are the like the equivalent of vector images for sound.

  31. Klimax says:

    @Spinoza: No plugins required – native support. At least for IE.

  32. Mario says:

    IE Team This isn't anything big and stuff but all i want to see if IE10 is the tabs toolbar to become more round like. cause the square shape of it looks very odd. plus round looks nice

  33. James says:

    var audio = document.createElement("audio");

    if (audio != null && audio.canPlayType && audio.canPlayType("audio/mpeg"))


    audio.src = "audio/sample.mp3";



    This is working great for me 🙂

  34. Aethec says:

    @All OGG fans: Sadly, there is no patent-free standard. Sorry. And WMA/AAC can be without DRM, too.

  35. Miguel Web Developer says:


    Microsoft Internet Explorer 9         –  130

    Microsoft Internet Explorer 10 PP 1   –   130

    unlocking what?? No change from 9 to 10

  36. Andrew says:


    I don't care if WMA/AAC music can be played without DRM. The fact that DRM is supported is the issue. Because they are supported, websites can easily force DRM onto their users anytime they want.

    Oh, and by the way, OGG is a patent-free standard. I don't see anything on the web that suggests otherwise. :/

  37. @Andrew says:

    So if a website want to use DRM, they should not be able to do it? lol. are you a retard?

    If users don't want DRM, they will move on to another site which offers without DRM.

  38. Andrew says:

    "So if a website want to use DRM, they should not be able to do it?"

    If a website uses DRM, then it may only be able to be viewed by a specific browser/OS. I know for a fact that my WMA files which I bought from NineMSN music a few years back could only be played with WMP, and are impossible to play now.

    Imagine what this will be like for web browsers? "Sorry, you can't view this video because you aren't running Windows. XYZ browser requires Microsoft Windows to view this content."

  39. Klimax says:

    Flash and Silverlight are laready hrer and with DRM support – we are already there Andrew. You are way too late to that discussion…

  40. Joe says:

    Will the <audio> tag in IE9 support the WAV audio format?

    HTML+TIME components used to support his in previous IE versions.  But since HTML+TIME has been removed from IE9, we need a suitable replacement and the current <audio> tag does NOT support WAV audio format.

  41. Aethec says:

    @Andrew: The fact Xiph says so does not make it so. Don't you think Microsoft was sure that Word didn't infringe i4i's patents, too?

  42. Eric says:


    OGG Vorbis is not a standard at all. It is a proprietary format owned by Xiph.

    It is free to use and has open specs.

  43. Neil Dunensach says:



    I agree with you, but don't expect Apple and MS to allow a royalty-free codec to live in their software.

  44. Andrew says:


    Read tools.ietf.org/…/rfc3533


    I don't see any reason to give up. Lots of people don't have Silverlight, and I already use Flashblock (which is incredibly useful).

  45. AndyC says:


    The Ogg container has been submitted as a possible standard (it's not one yet) but the Vorbis codec is an entirely different matter.

  46. Björn says:


    Nope, Microsoft apparently believed that the patent was invalid anyways because of prior use (alleged by them, denied by the i4s), at least that's what they said in court.

  47. Brent says:

    Thank you for supporting popular formates like Mpeg-4 and Mpeg-1.

  48. Andrew says:

    Interesting experiment that makes use of HTML5 Audio, Canvas and CSS3 transforms: