Play HTML5 audio in a browser

Playing HTML5 audio natively in a browser can be a challenge. Ashley Gullen, creator of HTML5 diversion editor Construct 2, guides we by a maze

This essay initial seemed in the May emanate (227) of .net repository – a world’s best-selling repository for web designers and developers.

Traditionally, anything audio-based on a web has played sound as a Flash applet. Now HTML5 is set to take over, and with Adobe interlude growth of Flash for mobile, many Flash developers are looking for new ways to do a things they used to in HTML5.
HTML5 is great, yet audio is one of a areas that’s still a work in progress. So, how does one play audio in HTML5? There are several options. One is the <audio> tag, upheld by all vital browsers. You can call this from JavaScript as simply as newAudio(‘music.ogg’).play(). But it’s designed for streaming music, and some browsers have issues with playback when it’s used heavily for things such as diversion sound effects. Here are a few some-more useful methods:

 var a = new Audio(‘sound.ogg’); – emanate new audio
 a.play(); – start playing
 a.pause(); – stop playing
 a.currentTime = 0; – rewind to beginning
 a.duration; – earnings length
 a.ended; – earnings loyal if finished
 a.loop = true; – set looping
 a.volume = 0.5; – half volume
 a.muted = true; – mute
 a.addEventListener(‘ended’, func); – call ‘func()’ when finishes playing

Since it was designed for music, the <audio> tag will always tide a audio from a server, so it might start personification before being wholly downloaded. For a full anxiety of the <audio> tag it’s best to go proceed to a spec – demeanour up HTMLMediaElement – or as always, a Mozilla Developer Network (MDN) has a good summary.

Realising the <audio> tag’s shortcomings, Google built a Web Audio API: a full audio engine with absolute routing, effects, sample-accurate playback and more.
It’s ideal for diversion audio, sincerely candid and many some-more absolute – yet takes some-more formula to get going and is now usually a W3C proposal. It’s also usually accessible in Chrome.
The following formula shows how to use Ajax to ask a sound and play it each dual seconds with a Web Audio API. Note a webkit prefix will be forsaken from AudioContext if it’s standardised:

  1. // This will usually be &lsquo;AudioContext&rsquo; if standardised
  2.  if (typeof webkitAudioContext == ”undefined”)
  3.     alert(“Web Audio API not supported”);
  4. 
  5.  // The context handles audio playback.
  6.  var context = new webkitAudioContext();
  7. 
  8.  // A sound buffer.
  9.  var dogBarkingBuffer = null;
  10. 
  11.  // Load dogbarking.ogg to a dog barking buffer.
  12.  var request = new XMLHttpRequest();
  13.  request.open(‘GET’, ’dogbarking.ogg’, true);
  14.  request.responseType = ’arraybuffer’;
  15. 
  16.  // Decode asynchronously
  17.  request.onload = function() {
  18.     context.decodeAudioData(request.response, function(buffer) {
  19.                                                                              dogBarkingBuffer = buffer;
  20.     });
  21.  }
  22.  request.send();
  23.   // Function to play one instance of the
  24.  // dog barking from a buffer.
  25.  function playDogBarking() {
  26.     if (!dogBarkingBuffer)
  27.          return; // not installed yet
  28. 
  29.     // Buffer sources are throwaway objects
  30.     var source = context.createBufferSource();
  31.     source.buffer = dogBarkingBuffer;
  32.     source.connect(context.destination);
  33.     source.noteOn(0);
  34.  }
  35. 
  36.  // Set a timer to play a sound each 2 seconds.
  37.  setInterval(playDogBarking, 2000);

Unlike the <audio> tag, this instance can usually play a sound once wholly downloaded (when a Ajax ask completes). But playback is present and many sounds can be played yet choking a browser, given a API was designed for this use. For some-more about a Web Audio API, check the HTML5 Rocks tutorial (the above formula is formed on this) or perspective the proposed spec at  for a full lowdown.

Mozilla, unfortunate with a Web Audio API, has due a MediaStream Processing API. This is a ubiquitous API for audio and video and it’s still a draft. No browsers support it yet, yet it has cold facilities such as audio constraint and regulating a board as a live video stream. Firefox also supports a comparison Audio Data API, yet it unequivocally usually allows essay samples to an audio buffer. This is too low turn to be of unsentimental use when building modernized apps such as games.

Some devs still use Flash to play audio with such shims as SoundManager 2. On mobile, native-app wrappers such as PhoneGap and AppMobi can yield their possess APIs too.
These might work for you, yet we’re meddlesome in pristine HTML5! So for now, a best proceed is to use the <audio> tag, yet we might also wish to use a Web Audio API in Chrome for some-more arguable playback.

Codec circus

You might have beheld a .ogg prolongation in a instance earlier, that was no mistake! This is a free, open Ogg Vorbis audio format, given Flash typically has used MP3s. Unfortunately, this brings us to another pain indicate in HTML5 audio: there is no singular audio format that all browsers support.

There are indeed 5 categorical candidates: uncompressed call files, MPEG-1 covering 3 (MP3), MPEG-4 AAC (or usually AAC for short, yet infrequently also called MP4), Ogg Vorbis, and WebM. Uncompressed call we can bonus loyal divided given a files tend to be too vast for web smoothness – you’ll leave users watchful for ages for them to load! Ogg Vorbis is identical to MP3 in record sizes and quality, yet unpatented and giveaway for anyone to use. WebM is giveaway and open like Ogg Vorbis, and indeed usually stores Vorbis in a opposite container, so let’s usually cruise it homogeneous to Ogg Vorbis for now. Ogg Vorbis also has a advantage of being some-more determined and obvious with wider support, given it’s now about 10 years aged contra a two-year-old WebM.

Play HTML5 audio in a browser

Lots of information and downloads for open codecs, such as giveaway encoders and decoders for a Ogg Vorbis format, can be found at xiph.org and vorbis.com

MPEG-4 Advanced Audio Coding (or AAC for short) is a law format that isn’t wholly giveaway to use – we contingency compensate fees and royalties if we discharge encoders or decoders. This isn’t a problem for many people building for a web, yet it can means issues for apparatus makers. For example, if we wish to make an HTML5 library or editor that helps we encode audio to AAC, we might need to pay. You can still secretly encode AAC files and discharge them on a web for free, yet – providing a obvious owners don’t change their mind. Finally there’s a informed MP3, yet a chartering might make it unusable: a MP3 chartering website states there is a price of $2500 for distributing a diversion regulating MP3 files! AAC is giveaway to discharge in games and is a improved peculiarity format, so there’s no reason to cruise MP3 and risk it – usually skip on right over to AAC (see What’s wrong with MP3, overleaf for serve details).

In short, a usually genuine possibilities are Ogg Vorbis and AAC. Chrome, Firefox and Opera support Ogg Vorbis. Chrome, Safari and Internet Explorer support AAC. So if we usually use Ogg Vorbis we skip Safari and Internet Explorer, and if we usually use AAC we skip Firefox and Opera. Whoops! Sadly a existence is we have to dual-encode all your audio to both Ogg Vorbis and AAC.

In your JavaScript, we can detect if a browser supports Ogg Vorbis with a following line:

  1. var canPlayOgg = !!(new Audio().canPlayType(‘audio/ogg; codecs=”vorbis”‘));

If canPlayOgg is true, bucket a .ogg chronicle of your files; otherwise, bucket a .m4a (the customary prolongation for AAC).

With browser-based technology, codec support is a same for all APIs (for instance Chrome plays a same formats with the <audio> tag and a Web Audio API). With non browser-native solutions, upheld formats will differ!

Why not one format?

There’s a bit of a deadlock with browser makers during a impulse over a audio format support. Mozilla righteously points out that a web is successful overdue to a giveaway and open nature. The internet might never have taken off if there were patents and fees on regulating a many technologies involved: HTML, a DOM, JavaScript, PNG, HTTP, TCP/IP and a browser itself, to name a few. On that basis, it refuses to supplement a law format to an differently giveaway and open web.

There is no technical reason that Internet Explorer and Safari don’t support Ogg Vorbis. It’s a giveaway and open format, and any browser builder can exercise it whenever it chooses to. The reason for a stand-off is quite political. Microsoft and Apple make their businesses around a proprietary. The emanate stems from a bigger fight over video formats, and a upheld audio format will tend to be whatever comes with a video. Video is out of a range of this article, yet Apple and Microsoft substantially mount to make income off a web by regulating a exclusive formats, hence their preference. Both sides like to advise that plug-ins can be used to support additional formats, yet apparently this defeats a plug-in giveaway knowledge of HTML5, so it isn’t unequivocally an option.

So this is a disaster for HTML5 developers, and something Flash developers didn’t have to understanding with. It is a small untimely yet dual-encoding to both formats solves a problem. The user will usually need to download one set of files depending on their browser’s support, so it won’t rubbish your bandwidth.

The best format for HTML5 developers is positively Ogg Vorbis, for a reasons Mozilla points out: we can use it openly and unlimited yet any regard over patents or licences. In fact, a HTML5 customary itself used to suggest Vorbis for audio and Theora for video in a Ogg container. But vigour from some of a companies concerned forced a recommendation to be forsaken and now a HTML5 customary does not discuss any formats, that has authorised this conditions to develop.

It’s a shame, given a giveaway formats are positively best for a web. HTML5 developers can assistance a conditions by pulling Microsoft and Apple to supplement support for Ogg Vorbis to their browsers. Make certain they know it’s your preference! With usually one format covering a whole web it will be many some-more candid to get audio operative in your HTML5 games and apps, and that will make life easier for everyone.

Mobile

Mobile devices’ browsers are some approach behind their desktop counterparts. As good as carrying weaker hardware, some can usually play one sound during a time – creation for a singular audio experience. iOS also adds that audio can usually be played on a user-initiated movement such as a symbol press, apparently to forestall autoplaying media regulating too many bandwidth on metered mobile networks.

Services such as PhoneGap and AppMobi offer native-app wrappers around HTML5 apps for mobile. Not usually does this capacitate we to tell to several phones’ app stores, they can yield ways around a device’s HTML5 audio limitations. Look into PhoneGap’s Media API or SoundPlug plug-in and AppMobi’s Player API.

Conclusion

In short, use the <audio> tag yet switch to a Web Audio API in Chrome. Encode to both AAC and Ogg Vorbis and you’ll cover all browsers with as small patent/licensing worry as possible.
While it’s best to support as many browsers as possible, in some situations we might be gentle with usually one. For example, if we privately aim Google Chrome, growth will be easier given we can use a Web Audio API and Ogg Vorbis audio exclusively. You’ll need to import a growth advantages opposite carrying a smaller assembly who can hear sound, though.

At this time there’s no transparent instruction over HTML5 audio: mobile support needs to be improved and it’s not transparent if a Web Audio API will be standardised. Personally we wish it does, given I’m meddlesome in HTML5 games and a Web Audio API is good for that. Mozilla’s MediaStream API could locate on or during slightest turn a improved choice to a <audio> tab in Firefox. Hopefully Microsoft and Apple will eventually support some form of Vorbis in their browsers, yet it’s distant from transparent – and let’s wish conjunction MP3 nor AAC finish adult holding over instead. So with HTML5 you’re going to have to keep adult to date: a second browser wars are in full pitch and things are changing quickly; be on a surveillance for changes and new technologies emerging

VN:F [1.9.22_1171]
Rating: 10.0/10 (1 opinion cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)
Play HTML5 audio in a browser, 10.0 out of 10 formed on 1 rating

Leave a Comment

Comments are moderated. Please no link dropping, no keywords or domains as names; do not spam, and do not advertise!


7 + seven =