HTML5.Audio - JavaScript MP3 Player Library (HTML5-like)

HTML5 allows <audio> element to play MP3 and other sound formats by HTML and JavaScript. But HTML5 is still not in major. So I wrote HTML5.Audio which is a JavaScript library to play MP3 music via Flash.

Demo #1: Play sound by HTML5.Audio

Demo #2: MP3 player

Before Using It


You can manipulate HTML5.Audio object like HTML5's Audio object.
To prepare it, load three JavaScript files on HTML header.
<script type="text/javascript" src="js/swfobject.js"></script> 
<script type="text/javascript" src="js/jkl-js2as.js"></script>
<script type="text/javascript" src="js/html5-audio.js"></script>

Plat MP3


Create HTML5.Audio instance with MP3 file URL. Then, call play() method to play it. It totally simple like HTML5's Audio object.
<script type="text/javascript"><!--

music = new HTML5.Audio('sound.mp3');
music.play();

--></script>
Note that HTML5.Audio library support MP3 files at this time.
WAV file and other sound formats are not supported. ActionScript's Sound class limits it.

Properties


HTML5.Audio library supports some properties imported from HTML5's Audio object: currentTime, volume, paused, ended, loop and duration
You need to call set()/get() method to set/get properties.
var ctime = music.get('currentTime');

music.set('volume',0.8);
Note that currentTime property will be updated only when playing music is started and paused.

Events


HTML5.Audio library supports some of events callbacked: onloadstart, onload, onplay, onpause and onended
You need to call set() method to set callback function for event property.
var onended = function () {
alert( 'sound ended' );
}

music.set( 'onended', onended );

Options


HTML5.Audio library loads html5-audio.swf flash file which was written by ActionScript 3.0.
To set path for html5-audio.swf, call getProxy() method before creating the first instance of HTML5.Audio.
<script type="text/javascript"><!--

HTML5.Audio.Proxy.getProxy({swfPath:'./html5-audio.swf',onready: init});

--></script>
Note that onready property is an event which will invoked when HTML5.Audio library was ready to play. You can call getProxy() method before window.onload event was invoked.

Files

  • js/html5-audio.js - HTML5.Audio library core (JS part)
  • js/jkl-js2as.js - JS-AS bridge (JS part)
  • js/swfobject.js - Library to load flash file
  • swf/html5-audio.swf - HTML5.Audio library Flash binary
  • swf/expressInstall.swf - Says install/update Flash!

Download


Check out files from the Spark project repository:
svn co http://svn.coderepos.org/share/lang/javascript/HTML5.Audio/trunk html5-audio


* Original post of this was written in Japanese at 2009/05/17 17:40