HTML5 Audio made easy

Jeremy Mansfield
December 6, 2011

I was recently tasked with creating a Christmas card landing page with the obligatory music auto-playing on page load, with cute little snowflakes tumbling down the page. Well, at least these snowflakes were creatively cute.

The issue that I ran into, like everybody else, is how to get rid of that doggone flash player <object> embed method and go straight to the html5 <audio> tag. Well, until Internet Explorer 7 and 8 just simply die, it’s not possible. So here’s a nice, easy and foolproof trick to overcome those pesky Microsoft browsers.

First, I added in the following code:

 

<audio src="music/file.mp3" autoplay></audio>

 

To add insult to the autoplay injury, I added in a loop. I know, Jeremy Keith won’t like it, but like Matt Lauer, he can suck it! So now my code looks like this:

 

<audio src="music/file.mp3" autoplay loop></audio>

 

And thanks to *FireFox not recognizing .mp3 files either, we need to use multiple “source” tags instead of the “src” attribute to offer the user’s browser a choice of multiple file formats. So now my code looks like this:

 

<audio autoplay loop>
  <source src="images/modified.mp3" type="audio/mpeg">
  <source src="images/modified.ogg" type="audio/ogg">
</audio>

*If you need help converting your audio file to the ogg format, I’ve been successful using this online resource.

For bulletproof IE audio capabilities, nest the <embed> tag within the <audio> tag. So now my code looks like this:

 

<audio autoplay loop>
  <source src="images/modified.mp3" type="audio/mpeg">
  <source src="images/modified.mp3" type="audio/mpeg">
  <embed src="images/modified.mp3" autostart="true" loop="true" hidden="true" />
</audio>

 

And there you have it, folks. You’re still stuck with the <embed> trick until Internet Explorer 7 & 8 die quick deaths … sometime in the next 10 years … I hope.

1 Comment
Josh Erickson
April 23, 2012

Nice post Jeremy. Thanks!


Work With Us?