HTML5 Audio Element
While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.
Thanks to the HTML5 audio element, gone are the days of having to use Flash to include audio files on a web page:
<audio src="deep-house-track.mp3"> </audio>
There are a few attributes you can use with the audio element. For example:
<audio controls loop autoplay preload="none" src="deep-house-track.mp3"> </audio>
- controls adds controls for play/pause, volume and seeking
- loop will repeat the playback
- autoplay does what you think it does 😈
- preload can take the values none, metadata or auto. The default is auto. It can be good to set it to none on pages where you include multiple audio elements, preventing the browser from downloading all the audio data.
Now, we’re not in a perfect world and you may want to provide multiple formats because mp3 is not an open format and therefore some browsers can’t support it. A free format, Ogg, would be great across the board, but it’s sadly not supported by all browsers. See here for a list of browser format support. Use the source element within the audio element to provide different formats:
<audio> <source src="deep-house-track.ogg"> <source src="deep-house-track.mp3"> </audio>
And you can be even more exhaustive by providing a type:
<audio> <source src="deep-house-track.ogg" type="audio/ogg"> <source src="deep-house-track.mp3" type="audio/mp3"> </audio>
And you can provide extra markup for browsers that don’t support audio:
<audio> <source src="deep-house-track.ogg"> <source src="deep-house-track.mp3"> <p>Your browser doesn't support this, <a href="…">download the file</a>.</p> </audio>
Can I Use audio? Data on support for the audio feature across the major browsers from caniuse.com.