Quick Tip: The HTML 5 Audio Element
videos

Quick Tip: The HTML 5 Audio Element

Tutorial Details
  • Difficulty: Beginner-Intermediate
  • Estimated Completion Time: 5 Minutes
  • Technology: HTML5

As of Firefox 3.5, Chrome 3, Opera 10.5, and Safari 4, we can take advantage of many of the new HTML 5 features, including native audio support without the need for Flash. As you’ll find, we only to create the new <audio> element, and set a few attributes. In this four minute video quick tip, we’ll review the mark-up, and also a quick way to play audio with jQuery.


The Audio Element

<audio autoplay="autoplay" controls="controls">
	<source src="file.ogg" />
	<source src="file.mp3" />
</audio>

The audio element accepts a handful of attributes, most notably:

  • autoplay : Immediately plays the file when the page loads.
  • controls : Displays the player on the page.
  • preload : Immediately begins buffering the file. (values = none, auto, metadata)
  • src : The path to the file name. It’s a better practice to load the file via the child “source” element instead.

Mozilla and Webkit don’t fully get along just yet, when it comes to the audio format. Firefox will want to see an .ogg file, while Webkit browsers will work just fine with the common .mp3 extension. This means that, at least for now, you should create two versions of the audio. I recommend that you use a quick and simple online tool, called Media.io, to convert your mp3 over to the ogg format.

When Safari loads the page, it won’t recognize that .ogg format, and will skip it and move on to the mp3 version, accordingly. Please note that IE, per usual, doesn’t support this, and Opera 10 and lower can only work with .wav files.


Loading Audio with jQuery

// Slightly modified from video version.
$(document).ready(function() {
    // Create an audio element, and set it to autoplay,
   // and show the player when the page loads.
    var audio = $('

Please note that we can go much, much further with this, including how to stop the audio, change the volume, etc. This quick three minute tip is just to whet your appetite. If you’d like to delve deeper, let us know and I’ll schedule a full thirty-minute tutorial on the topic!

Add Comment

Discussion 63 Comments

  1. Interesting… I wonder how the same can be done with IE?

  2. Gupocca says:

    Looks good, I’ll have to read it soon. I haven’t played around much with HTML5… I should.

  3. What’s the song in the demo? I love 8-bit music.

  4. Nice tutorial. It would be nice to see more tutorials with HTML 5 features.

    Cheers!

  5. Jason says:

    It works in Opera 10.50 too :)

  6. esranull says:

    what is this? I dont understand

  7. DuMmWiaM says:

    Any tips about preloading all the sounds, before accessing them?

    • Daverix says:

      You could let the audio-element be in the page instead of creating it on the fly and set autobuffer=”autobuffer” on it. Then when you want to play the element you could call play from an onclick method on the link instead.

      More simpler example

      document.getElementById(‘playButton’).onclick(function() {
      document.getElementById(‘music’).play();
      });

      Play music!

  8. Benje says:

    Total win with the Zelda theme song. ;)

  9. Help Please says:

    Mp3 work with this in Firefox but i am having trouble in opera anyone help?

  10. Mike T. says:

    Can you please edit the article and remove the `autobuffer` attribute? It’s no longer in the html5 spec and has been more or less replaced by the `preload` attribute.

    Sadly, when blogs this popular publish inaccurate information, the open web suffers.

    http://www.w3.org/TR/2010/WD-html5-20100304/video.html#attr-media-preload
    http://www.w3.org/Bugs/Public/show_bug.cgi?id=8731

    • Jeffrey Way says:
      Author

      I think that’s rather harsh. This is a barely documented update that was made to the spec less than 10 days ago. Nonetheless, I’ve updated the tutorial accordingly. :)

      • Mike T. says:

        I’m not sure if it’s harsh or not–but when stale or incorrect information is presented as current and correct, just think of all the bad markup that results.

        Thanks for making the change, though. :)

  11. [quote]As of Firefox 3.5, Chrome 3, and Safari 4,[/quote]

    You forgot Opera 10.5, which was released a few days ago.. it works too.

  12. Great tutorial. Any way to style the audio player like people have been styling the video player such as over at http://jilion.com/sublime/video

    Also, I like the facelift Nettuts just got! Looks like the whole tuts network just upgraded.

  13. David Moreen says:

    That is really really cool, down with flash! Down with flash!!!!

  14. Stephen Webb says:

    HTML 5 certainly seems an exciting development of the HTML framework. With abilities like these (which will quickly overshadow Flash for small tasks) it seems that HTML 5 will increase development speed and the general possibilities in web design.

    It is a shame that IE is holding the mainstream usage of this back for the moment. All these new technologies are fantastic as long as the browsers support them, and until IE does so we can only use these with caution. Hopefully this will be resolved with the upcoming release of Internet Explorer 9.

    With this giving a hint of what is to come in HTML 5 I am intrigued to see what other developments come with the framework. Maybe covering these in a future post would make a great article.

  15. Cody says:

    Uh guys – IE doesn’t support this because it’s not even a set standard yet. IE isn’t holding anything back at all; it’s just these guys who should have better things to do like making money for their work rather than f*ing around with unsupported standards.

    Flash is still the best way to go for providing cross-browser/platform audio and video support.

  16. Wow..

    That’s good !

    Thanks !

  17. Michael says:

    Thanks for this great tutorial, , thanks for sharing it!

    Do we need to include an ogg and mp3 for every piece of audio we want to include using this new method in order to maximise compatability?

    You might want to include the word ‘need’ in the second sentence of the opening paragraph …

  18. That is awsome, I am looking forward to all browsers recognizing HTML5

  19. Martin says:

    This isn’t exactly on topic, but is there a special reason to make the click callback function return false, instead of using event.preventDefault() ?

    http://api.jquery.com/event.preventDefault/

  20. Fernando says:

    great zelda´s song….

  21. Erik says:

    nice tip and totally love Zelda… Jeffrey ftw!

  22. Axel says:

    It is’t work in IE8, very bad))

  23. Callum says:

    You’ve used incorrect syntax. You close the source tag using the XHTML closing slash. Should just be:

  24. Bujar says:

    hey can some1 tell me how how to group my dock like he did at 2:05 min.??

  25. Axel says:

    you can just write:

    it’s work too

  26. nXqd says:

    It’s really nice and simple tutorial :)
    Video and audio supported with HTML5 is good .

    -nXqd-

  27. Steve Durr says:

    Nice. I was walking in to work this morning with my iPhone and iPod in hand when I felt it is now time to have all my music on the web and listen to it via the iPhone or browser.

    Perfect tut.

    @Axel @Jordan Walker

    You guys could try this

    http://net.tutsplus.com/tutorials/html-css-techniques/how-to-make-all-browsers-render-html5-mark-up-correctly-even-ie6/

    I haven’t got round to it yet but the title implies it could help you out.

  28. Vin says:

    If I don’t have an audio file, but just an audio stream in memory, e.g. byte [] audioBuffer, How can I play it without saving that into a file?

    Thanks

  29. My3rdGradeShirt says:

    Unfortunately the “SRC” attribute exposes the audio file URL very blatantly, allowing anybody to grab the file. I haven’t found a way to hide the SRC or at least obfuscate it to a decent level. If anybody knows a way without flash speak up.

    • Jesse Price says:

      You would have to use some server side scripting such as php and deny direct file access. The source would have to look like src=”/music.php?song=blah”

      Your PHP would have the mime type and header content types for whatever audio file and in the script would simply check the user agent etc. In the header of that PHP / server side script would contain a conditional to exit / die on direct script access. You could also mess around with permissions on that file as well.

  30. Trench says:

    Is it easy to stream audio with this tag? If so, are there any web resources to describe how to do this?

  31. Pritam Pebam says:

    Is there a way to customize how the controls look, maybe using CSS??

  32. Jesse says:

    With all these browsers and their own special quirks and IE ALWAYS so far behind, makes me truly believe in the claim and rumors that HTML5 will roll out in 10 years (probably providing MS the time to ditch ie and build on webkit such as Chrome). This is so disappointing since web applications could be much more elegant. And I do agree with some of the comments with the src tag being visibly accessible to the client end. Makes me wonder if more encryption and other methodologies will exist in HTML5. I worry about this since I had some jerk hotlink my jquery file and got mad traffic which made me shell out an additional 80 bucks one month on bandwidth (455GB out and was not monitoring). Maybe it was a good thing since it forced me to tightened up my security tighter than Kelsie’s *you know what*… oh well… HTML5 is already being used and implemented such as the latest wordpress… HTML5 still has WAYS to go… I’m still wondering about the … why not HTML5 ? so are we also waiting for an official doctype syntax?

  33. DK says:

    Great tutorial!
    I’ve been trying to figure out a way to have music play uninterruptedly even when surfing through different pages on a music site (it’s a musician site and it would only play when the play button is pushed). I had just about given up hope on finding any way to get continuous music that didn’t involve popping the player up in a new, separate window. Then I came across amiestreet.com, whose player comes up at the bottom and seems to be just a div within the main page code, AND it plays continuously! But I can’t figure out how they accomplished this! (I’m not terribly well-versed in jquery or javascript)

    So…is it possible to code an audio player to play continuously through page loads using just html and jquery?? If so, how? If not, any idea what other code they utilize on a site like amiestreet?

    Thanks for any and all insight! This problem has been driving me absolutely nuts!
    ~D

  34. game says:

    i am having trouble in opera anyone help?

  35. Hey,

    how much longer shall we all be dominated by the technical degrees coming up with any IE?

    If not we as the developers carefully tell all users which browsers are up to date – who else? Microsoft? ;-)

    We shouldn´t keep hidden all the time, we should say “If you are using the IE, you will not can enjoy the internet” Why don´t we all do that definitive? Why don´t we finally make it public what it´s about with the never ending story of Microsofts IE? Why are we still afraid?

    Only we can do this! For a better internet! Otherwise the most users will get on with the IE forever and we have to hack! Why? Let´s stop that!

    What do you think?

  36. Nikhil Varma says:

    Hi Jeffrey Way,
    Your video was impressive. Could you please tell how i could bring sound on mouseover in my website which is powered by WordPress. I want a particular sound track to be played for hovering the mouse over a particular paragraph and another sound should be played when the mouse is hovered over the next paragraph. Your video makes me believe that a small change in your code might help to get what i want( Probably a ‘Mouseover’ instead of ‘click’). And please tell me how i can incorporate it with wordpress. I am sure that you’d be able to help me.

  37. ryoo says:

    nice thanks!!!!

    is it possible to style the html5 player?
    thanks

  38. Aszazin says:

    IE9 will support it (or already does)

    Always a latecomer…
    But no reason not to use the tag when building a new site. It won’t be long before anyone can use it… (although holding back isn’t a bad idea… including 3 video formats & 2 audio formats to stay compatible isn’t exactly developer-friendly…)

    oh yea, the tip says to ‘convert your mp3 over to the ogg format’… please no… don’t recode an mp3 to ogg vorbis, or an ogg vorbis to an mp3…, take the original ‘uncompressed’ and code it from that one twice. recoding means loss of quality and should be avoided, unless a compressed format is the only existing source…

    ogg tends to sound a lot better than mp3 at lower & normal bitrates. So let’s hope the commercial players adopt it…

  39. Mike says:

    I find it hilarious that you think Chrome’s player looks better than Safari’s. Safari’s media player clearly is the most simple, minimal of the three which is exactly what a default player should be. I guess there’s no accounting for taste.

  40. db says:

    Thanks for the info! I’ve just begun experimenting with CSS3/ HTML5 on a test site for my music and one video.

    I’m using .mp3 and .ogg versions of each song. It works great in the latest Safari and Firefox and the browser only loads the relevant file.

    However, when I include multiple versions of video (.mov, .ogg.ogv, .mp4) all of the files attempt to load on the page. I haven’t figured out a way to load only one version.

    I’d also like to be able to style the audio controls using CSS. I had partial success using this basic code:

    audio
    {
    width: 250px;
    background-color: #340000;
    }

    It only appears to work in Firefox. Oddly, it doesn’t color the entire element. The color is muted (blended with the grey?) and leaves a grey bottom border. I like the effect but hope to find a global styling solution for the controls.

    thanks again

  41. Alex says:

    thanks. enjoyed the post .. here is another usefull stuff

    All about html5, templates,news,apps everything here.

    http://html5arena.blogspot.com/

  42. oddant says:

    hey this is cool, to when the time we will be allowed to change the icon of control buttons ?

  43. Lol says:

    This is soooo much more work than making it in flash. And you even end up creating your project in flash also in case the browser does not support html 5? This is very unnecessary. Being anti flash is a fan boy trend for noobs who need something to shake a stick at. Do you really want to create your sound as a wav, and a .ogg then also create the sound app in flash to get your point across?

    HTML 5 , please be more sensible.

  44. smt says:

    i want to add a class to all div elements with an audio element..
    Can someone please send me a code..

  45. Mister X says:

    Great thank you. This is what I was looking for for our Radiostation to build a player to stream our Channel X radiostation for iPhone’s.

    X-stream

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.