The HTML <audio> tag is a relative newcomer amongst the HTML tags we use regularly. It was introduced to help correct what seemed to many, myself included, like a major oversight of the modern web: native audio support by browsers. A wide variety of image formats have been available via the <img> tag since soon after HTML was initially developed, but digital audio and video were initially too heavy to be used in HTML pages intended for the public. However, today we finally have both an <audio> tag and a <video> tag. Problem solved, right? Nope. Unfortunately, there are still a number of bugs to work out, mostly with browser interoperability. The root of this issue is a lack of a standard file format.
But, I’m a modern web developer. I’m not going to use some Flash shiv to get my page playing audio! It took some troubleshooting but here’s how I did it:
First of all, it’s important to know a bit about how the <audio> tag works. It can either stand alone or act as a container. A standalone audio tag would look like this and appear familiar to any web developer:
<audio src="bach_brandenburg_5-1.mp3" controls preload="auto" autobuffer></audio>
The above tag will show controls for an audio file, buffer it, and allow it to be played. If only it were that easy. This will only work in IE 9+, Chrome 6+, and Safari 5+. In Firefox, Opera (although this may change with the switch to Webkit), or any older browser it will silently fail.
The problem is that neither Firefox nor Opera support MP3 as a file format. In fact, there is currently no single file format which can be played natively by every modern browser. IE, Chrome, and Safari can handle MP3, Chrome, Firefox, Safari, and Opera can handle WAV (but do you really want to use WAV?), and Chrome, Firefox, and Opera can handle OGG. So you’ll need both an MP3 and an OGG copy of every audio file you want to use. I used media.io to convert my MP3s to OGGs.
<audio controls preload=”auto” autobuffer>
<source src=”bach_brandenburg_5-1.mp3″ />
<source src=”bach_brandenburg_5-1.ogg” />
Unfortunately your browser does not support our audio formats.
It turns out that the <audio> tag can be the container for multiple <source> tags each of which can define a different format. The great thing here is that so far in testing, all the browsers I’ve used have simply ignored the formats they couldn’t read and played the one they could. The text is a fallback if the browser fails to render the audio controls (old browsers, mostly).