07 May 2013

Detecting Browser Support for HTML5 Audio Autoplay

I love to play with audio and I love to build web applications. Also, my new year’s resolution for 2013 is to make everything that I build work in mobile. Unfortunately the HTML5 audio element and mobile web browsers are quite at odds with each other. The biggest problem is the inability to play audio without a user click event, and relatedly the inability to use the autoplay attribute, which happens on both iOS and Android.

Since the SoundCloud HTML5 Widget uses the same features it has the same problems, and only plays if you manually click the play button inside the widget.

After wrestling with this for a while, I finally accepted that I’d have to treat mobile differently, so the new problem was determining if a browser supports autoplay or not. My first approach was to look at navigator.userAgent and apply logic accordingly. However, I later came up with the following code snippet, which tries to immediately play a dataURI audio file, and if it succeeds, it sets the global variable AUTOPLAY to true.

It always feels great to delete code that employs useragent hacks. Here’s the code:

So far it’s working well, and I’m using it on a pet project of mine called PicDinner (on github) to manage whether I immediately play a song or show the user an interface to trigger the play action.

Did you find this helpful or fun? paypal.me/mrcoles
comments powered by Disqus

Peter Coles

Peter Coles

is a software engineer living in NYC who is building Superset 💪 and also created GoFullPage 📸
more »

github · soundcloud · @lethys · rss