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: