HTML5 audio for games made easy

Published October 20, 2014
Audio in the browser is deceptively tetchy. It's easy to get a basic sound to play with the .[code=html:1]
But there are several problems with this:

  • First of all, good luck navigating this compatibility chart. Until Mozilla finally caved and decided to support MP3, there was no single file format supporting Chrome, Firefox, Safari, and IE. Opera is still a painful holdout on file formats, and the situation on mobile is disgusting.
  • You can't programmatically trigger the audio playing on mobile devices without direct user action in your game loop. You basically have to put up a "start game" button that tricks the user into playing a silent audio file, then you have free reign to trigger that particular audio element.
  • You get almost no control over how the file plays. There is a volume setting, but it hasn't always been reliable on all platforms. There's no mixing. There are no effects.
  • It's super difficult to rewind and replay an audio file. Honestly, I still don't really know how to do it correctly, and I'm a goddamn salty pirate.

    In short, the
4 likes 6 comments

Comments

Comments are shown oldest first so the discussion reads top to bottom.
EDI
EDI

Good post; I've been doing html5 game stuff since early 2012 and its come a long way since then.

While a bit out of scope it might be worth noting that doing singular file requests for sound effects; is likely to result in poor performance in a production environment.

I've found instead using an 'audio atlas' which is a pre-made 1D array of sound effect files; with an associated mapping of file id to start position and duration.

This way, to play a sound you simply instruct webaudio to seek to a position and play to a duration.

-Raymond

October 21, 2014 01:41 PM
capn_midnight

That's a good idea. And yes, with Web Audio, it shouldn't be difficult.

My goal with this was to just get a bare minimum of useful audio together. The Web Audio API is extensive, but for throwing together quick demos, 80% of it is unnecessary. This JS file is for that 20% use case, wherein the <audio> tag is completely useless.

October 21, 2014 09:09 PM
tnovelli

For a completely different approach, you can generate retro sound effects (like BFXR) with WebAudio... I made a decent start: http://tnovelli.net/junk/synth2.html

October 22, 2014 01:43 AM
capn_midnight

Very nice, but you shouldn't use <progress> elements like that. You should be using <meter>.

October 22, 2014 01:52 AM
Eck
Eck

Very cool post sir. Thanks for sharing.

October 23, 2014 02:37 AM
capn_midnight

You're welcome!

October 24, 2014 01:32 PM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!