Handling HTML5 Audio

I’ve been toying with a game idea recently. I’m prototyping in HTML / JS / CSS to test out the game mechanics. My goal is to have the game run natively through Titanium but also in a browser too. This means I need a lot of facade patterns for the game libraries themselves.

One of the first roadblocks I ran in to was HTML5 audio. This spec is so poorly implemented across mobile browsers it’s viritually impossible to use for something like a mobile game. I’m not alone with the shortcomings too, check out some of these articles:

It should be as easy as this right?

[gist id="5892327" file="audioHTML5.js"]

Well, it sort of works, except you can’t play that sound over and over again on Android. e.g. Think about a character attacking an enemy over and over, you need to play a sword smashing sound, armor clanking, etc. Yeh you can’t do that in Android mobile browsers without some crazy tweaks. It doesn’t even work consistently in an iOS webView (mobile safari). It does work in any modern, desktop browser I’m targeting. Enter the audio facade.

I decided I can use html5 audio when it’s on the web and use the native audio API’s when running through Titanium. Real quick context: The game runs in a webView, so fireEvent is needed to talk back to the JavaScript context in Titanium. Easy peasy:

[gist id="5892327" file="playSound.js"]

The Titanium playSound event would then look something like this:

[gist id="5892327" file="app.js"]

Now I can fire my audio files off without a worry if I’m in the browser or native app via playSound(MySoundFile).

Posted In:
Post Details