How to use Cross-browser HTML 5 audio

HTML5, the next generation of the web mark-up language, is a wonderful thing. It’s a true step forward to mak browsers more powerful and easy to use. From now on I will launch a major website completely in HTML5. Working on that, I foudn out some interesting features of the audio tag.

html5 Internet Explorer

html5 Internet Explorer

The new audio capabilities of HTML5 are a godsend. It means not having to embed a flash player anymore, since the browser can play audio natively. Well ….. not quite. Not all browsers can play all media types. Unfortunately browser makers are involved in a policial discussion, which severely limits our options.

This means workarounds for something that can be so beautiful. Anyway, the benefits outweigh the drawbacks for me, so here’s my quick guide on how to embed audio in HTML5.

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

This is all you need. Or rather, all you should need. Firefox does not play MP3, so you will need an OGG file if you want audio in that browser. This is where the source element comes in:

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

Works rather well, provided you start with the OGG first because of a Firefox bug. But what happens when you only have an MP3?

Firefox will show the player, but will be unable to play. Your users are stuck with a broken page. Apparently, this is intentional. Well in my opinion that sucks donkey balls. If you can’t play the media, don’t show the controls! So in order to resolve this I had to implement a workaround. Since my fallback option (visible for IE users) is to render a simple link, this is what works for me, when I embed just an MP3 audio file without OGG variant:

/* If the browser does not support MP3, remove the audio tags completely.
   needed for firefox  */
if (document.createElement('audio').canPlayType) {
	if (!document.createElement('audio').canPlayType('audio/mpeg')) {
		$('audio').each(function() {
			$(this).after($(this).find('a'));
			$(this).remove();
		})
	}
}

(preferably inside your jQuery document ready event) It removes the audio element completely and inserts the fallback content into the page. Works like a charm.

Incoming search terms:

  • cross browser audio player
  • html5 audio cross browser
Share
8 visitors online now
3 guests, 5 bots, 0 members
Max visitors today: 16 at 01:56 am UTC
This month: 74 at 04-21-2017 07:18 pm UTC
This year: 74 at 04-21-2017 07:18 pm UTC
All time: 513 at 06-01-2016 02:24 pm UTC
Get Adobe Flash player