Mastering the HTML5 <audio> tag

by Jean. 34 Comments -

Since internet connections are fast enought to play sounds on websites, Flash has been the tool of choice for anyone who wanted to play sounds on a website. But HTML5 is going to change the way developers can play sounds online. In this article, I’m going to show you in depth how to use the <audio> tag to play sounds on your website.

Using <audio> to insert a sound file on your website

Here is the most basic use of the <audio> tag: On this example it loads a mp3 file and play it. Notice the autoplay attribute which is used to play the sound automatically. That said, you shouldn’t play sounds automatically on a website: this is extremely boring for visitors.

<audio src="sound.mp3" autoplay></audio>

Play sound in loop

Want to loop a sound? The loop attribute is here to help. But once again, you shouldn’t abuse autoplay and loop playing if you want to prevent people from prematurely leaving your website!

<audio src="sound.mp3" autoplay loop></audio>

Display browser controls

Instead of playing sounds automatically, which is definitely a bad practice, you should let the browser display some controls such as volume, and a play/pause button. This can be done easily, simply by adding the controls attribute to the tag.

<audio src="sound.mp3" controls></audio>

Multiple file formats

<audio> is supported by most modern browsers, but the problem is that different browsers do not support the same file format. Safari can play mp3s, but Firefox can’t and play .ogg files instead. But Safari can’t play .ogg files…
The solution to this problem is to use both formats, so visitors can hear your sound, whatever the browser they use.

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

Specify MIME types

When using different file formats, it is a good practice to specify the MIME type of each file in order to help browser to localize the file they support. It can be done easily, using the type attribute.

<audio controls>
  <source src="sound.ogg" type="audio/ogg" >
  <source src="sound.mp3" type="audio/mp3" >
</audio>

Fallback for old browsers

And what if the visitor still use IE6, or another prehistoric browser with no support for the <audio> tag? A fallback can be easily implemented: As shown below, a message will be displayed to browsers who do not supports the <audio> tag.

<audio controls>
  <source src="sound.ogg" type="audio/ogg" >
  <source src="sound.mp3" type="audio/mp3" >
  Your browser does not support the audio tag!
</audio>

Buffer files

When playing large files, it is indeed a good idea to buffer files. To do so, you can use the preload attribute. It accept 3 values: none (If you don’t want the file to be buffered), auto (If you want the browser to buffer the file, and metadata (To buffer only metadata when page loads).

<audio controls>
  <source src="sound.mp3" preload="auto" >
</audio>

Control HTML5 <audio> with JavaScript

Controling a HTML5 audio player with JavaScript is pretty easy. The following example (Taken from Jeremy Keith book HTML5 for WebDesigners) shows how you can buid an audio player with basic controls (Play, Pause, Volume Up, Volume Down) using HTML and JavaScript.

<audio id="player" src="sound.mp3"></audio>
<div>
	<button onclick="document.getElementById('player').play()">Play</button>
	<button onclick="document.getElementById('player').pause()">Pause</button>
	<button onclick="document.getElementById('player').volume+=0.1">Volume Up</button>
	<button onclick="document.getElementById('player').volume-=0.1">Volume Down</button>
</div> 

That’s all for today. I hope this article helped you to understand what you can do with the HTML5 <audio> tag. Any questions? Feel free to leave a comment below!

  • http://illution.dk Frederik Lassen

    Please correct .pause) to .pause() :D

    • http://www.wprecipes.com Jean-Baptiste Jung

      Done, thanks!

  • kayan

    I’d like to read a writeup on how to use something like MediaElement.js to make the audio element work cross-browser.

    I stopped attempting to use the audio element because of cross-browser compatibility problems. However, there is now software like MediaElement.js, which will let you use the audio element, and gives you a flash audio player with same API to make it work cross browser. I plan on using that the next time I build a website that plays audio.

  • Ralf

    Hello Jean-Baptiste,
    first things first… thanks for another great post – every important detail about the audio tag in one place ;)
    … but there are a few typos in your js example? missing quotes, braces…?

    • http://www.wprecipes.com Jean-Baptiste Jung

      If you found a typo/bug, please let me know so I can correct it ;)

      • Ralf

        Volume down: you forgot to add “-=0.1″… and you should wrap the value of the onclick attribute into ” quotes ” … mé C po tro grave ;)

  • http://www.madrasgeek.com Madras Geek

    well written, simple and great tips. Bookmarked for instant lookup. All your posts have made me to bookmark, each one is so useful. Thank you so much sharing!

  • Estrella

    When do you play an audio with .play() does it reload the sound file again?

    • http://www.wprecipes.com Jean-Baptiste Jung

      You have to use the loop attribute to do so.

  • http://kerryj.com KerryJ

    Thanks so much for sharing your expertise! I’m happily using this tag on my site.

    Merci beaucoup!

  • http://www.100webhosting.com Jasmine

    HTML5 audio is great. I still remember it was so difficult to play an audio file in the old days. :)

  • http://lazaac.com lazaac

    yeah, waiting for video in html5 tutorial and explanation…

  • http://gravityformscoupon.com/ Mike

    I am looking forward to experience the enhanced client side data caching features that HTML5 offers. This should definitely help to build mobile client applications that use a lot of caching and off lining. The other great feature is how vector graphics can work independent of the browser. This should get rid of flash/flex technologies and will offer uniform experience to analytics/charts/reports applications.

    HTML5 rocks!

  • http://www.tipsum.com Tipsum

    Is there a way by which this would work on older browsers as well? Some sort of a flash fallback like how youtube does it?

    • jack

      I assume between the tags you could embed a YouTube video, which older browsers could play. If their browser is so old it can’t play YouTube, they shouldn’t be listening to audio files with more than 8 bits anyway :)

    • Bruno Mateus

      Most of the problems in old browser come for Internet Explorer users. For those, you can either:

      – use an tag that falls back to the usual Flash or Quicktime plugin.
      – alert users to upgrade to newer browsers. I usually direct users to Google Chrome Frame for IE ( http://code.google.com/chrome/chromeframe/ ) – this will help them use almost all html5 tags on the code like if it was Chrome. Problem is, people don’t usually bother installing it…

      It should always be the last line inside the tag, like specified in this article, on the Fallback section.

  • Jack

    Disappointing article. Not “in depth” as was claimed in the first paragraph. And to say that “HTML5 is going to change the way developers can play sounds” is both misleading and debatable.

    • http://www.waseemsakka.com Waseem

      I don’t see how it can be misleading or even debatable. Sure, not ALL developers will adopt HTML5 streaming now, but it’s still early. In two years, it’s hard to imagine any other technology being used to stream audio being more widely adopted than HTML5. HTML5 has allowed mobile app makers to use frameworks such as PhoneGap to easily stream audio and video to their ‘non native’ apps as an example.

  • gabriel

    sorry, but what if i want play two or more songs?

  • Greggormac

    I’m using the tag and my browsers play it no problem, but my friend (Who is using IE 9) plays it, and it looks like it is playing, but no sound is coming out of the speakers. Other websites, like ‘Pandora’ play well, so it looks like it is just the tag we are having problems with. Is there some type of setting in IE9 that he needs to change?

  • Peter

    Great. I just updated my website as nowadays are browsers with HTML5 audio support wide spread enough to make the changes in my code :-) Things got much simpler.

    Just one little addition to the article: if you DO NOT WANT the browsers to cache the audio file just append a “?something” to the filename. For example: src=”sound.mp3?123″

  • http://www.moxby.org.uk/ Martin Oxby

    Do we know for definite if the file types supported has improved since you wrote this post? Just putting a site together and trying to avoid a complicated jQuery option to improve page speed, but if MP3 and OGG are still the only supported types I may have to go down that route.

    Thanks!

  • Phil

    Did the HTML5 guys forget about system sounds?
    How do I not provide my own sound files, but use the system’s default sound scheme to play a sound for SystemAsterisk, SystemQuestion, etc… ?

  • Rakesh

    Hi Ralf ,

    I tried to load the .wav audio file using HTML 5 audio tag. html page is not loaded. Is audio tag supports .wav format?

    Awaiting for your reply.

    Thank you
    Rakesh

  • http://www.summitweb.net/ Martin Oxby

    To be honest you don’t want to use .WAVs in websites anyway because of the filesize. Consider using a different format to keep load speed down.

  • brenda

    hello

    If i want the html player to trigger an event using the on play attribute eg to show the name of the song being played in the progress bar in the html 5 player, what should i be doing.

    I am migrating from flash for 12sites showing songs and also moving to another server.

    I have had many demands for a mobile friendly/android friendly player so………after hours of uploading and renaming, I seem to have hit a coding block…

    Any helpers are appreciated.

    eg to play one song my code is saying

    Your browser does not support the audio element.

    This works fine

    However once the song is playing i want the song name to show in the control bar

    Should i be using a css style sheet to style the player separately?

    I am hoping the simpler and cleaner the code the less the strain on my already strained mind

  • http://allsnoringcures.com Sisir

    Volume up and down function comesup with an error on console when it reach it limit. What is the fix for that?

  • Anderson

    Easy! Great!

  • Charles C

    What simple in line javascript would you use to skip forward or previous? Please help!!!
    Thanks ahead of time.

  • http://www.FoolQuest.com Aaron Agassi

    How to I set a numeric integer (instead of infinite which is the default) to control how many times the autoplay sound loops?

  • Greg Roby

    I want to auto play a sound file the first time the visitor lands on the page but not play on return visits is this possible.

  • kamlesh

    Hi Dear,

    I want to set image as play button how to do that?

  • Allison Reames

    Whenever I navigate to a new page within my app, the music from the first page continues playing, even if I press play for another song on another page. How can I stop the music from the first page? Thanks!

  • Tosan Ilkom

    how can i play two audio files in sequence?