Thursday, February 28, 2013

HTML5 Audio

Been playing around with HTML5 audio recently. If you're new to the <audio> tag, this was introduced with HTML5 in order to allow native audio support. Having built in widgets to control audio is great, but the underlying AudioContext library is where the real power is. I'm still playing with the AudioContext library, and should have something more to say about this in the near future. But, for this post, we'll focus on generating a <audio> tag, and some of the important things that you can do from the scripting side to control the functionality and react to events.

A quick table and descriptions of useful attributes:
AttributeDescription
srcThe URL to the audio file
durationThe length, in seconds, of the track. You will get trailing decimals for the exact length of the track (it's not rounded off)
pausedTrue if playback is paused, false otherwise
autoplayWhen set to true, the track will automatically start playing when enough of the track has loaded
controlsWhen set to true, a control widget is rendered on the HTML page


Here's an audio tag that isn't hooked up to anything, but has the controls enabled:

Useful methods:
MethodDescription
play()Starts audio playback
pause()Pauses audio playback


Note that there is no stop() function. However, I think this is a reasonable way to mimic stop:
  function stop(audioElement) {
    audioElement.pause();
    audioElement.currentTime = 0;
  }

Useful events:
EventDescription
playCalled when the audio track begins playing
pauseCalled when the audio track is paused
endedCalled when the audio track has ended


Here's a code snippet instantiating an audio element using Javascript:

  // Create an <audio> element dynamically.
  var audio = new Audio();
  audio.src = 'file.m4a';
  audio.controls = true;
  audio.addEventListener('play', function() { isPlaying = true; }, false);
  audio.addEventListener('pause', function() { isPlaying = false; }, false);
  audio.addEventListener('ended', function() { isPlaying = false; }, false);

  document.body.appendChild(audio);

In this example, I create an audio tag with a source file pointing locally to "file.m4a". Controls are enabled and visible when the page is rendered. I also add 3 event handlers that simply toggle a state variable that shows whether the track is playing or not.

This scratches the surface of what you can do with HTML5 <audio>. Later, I'll get into tying <audio> with the AudioContext object for sound mixing (filters, panning, gain, etc.) and visualization (frequency and amplitude graphing). Think of this as the tiny tip of a very, very large iceberg.

No comments:

Post a Comment