The audio Element
Adding audio to an HTML5 page couldn't be more simple. At its most basic, the tag looks like this:
However, the above code would not do anything or even show up on the page.
To give the user the ability to play and pause the audio, you need to add the controls attribute, which can be minimized as shown in the following demo. Open the demo in Chrome, IE9 or Safari to see it work.
If you open the last demo (html5-audio-and-video/Demos/audio-controls.html in Opera on a Mac, the controller will look like this:
That's because Opera (on Mac or PC) does not support the MP3 format. Recent versions of Firefox, running on recent versions of Windows, do support the MP3 format; Firefox on a Mac does not support the format.
Browsers that support MP3
- IE (from version 9)
- Firefox on PC
Browsers that support OGG
Instead of using the <audio> tag's src attribute, you can nest one or more <source> tags within the <audio> tag, each with its own src attribute and a type attribute to let the browser know if the file is of a mime type that it supports (and therefore should bother loading). Browsers will use the first file they support. The code sample below shows how to make our audio tag work in all HTML5-compliant browsers.
||Points to the audio file. Only used when there are no nested source elements.
||Boolean. If present, indicates that controller will be displayed.
- auto: Browser should choose whether to preload the file.
- metadata: Browser should only preload the metadata as the user is likely not to need the file. This is the default.
- none: Browser should not preload anything as the user is likely not to need the file.
||Boolean. If present, audio will begin to play as soon as it has loaded.
||Boolean. If present, audio repeats indefinitely.
We have already discussed the src and controls attributes.
The preload attribute is relatively self-explanatory. You should set it to "auto" if you know the browser will need to download the file. Otherwise, you can most likely leave it out or set it to "metadata" (the default).
You can get the audio file to play in the background by removing the controls attribute and adding the autoplay attribute as shown in the following demo.
And the loop attribute simply makes the audio file restart again when it reaches the end.