Archive for the ‘HTML5’ Category

How to make an HTML5 music player / Using the audio tag

July 7, 2010

There has been a lot of noise about HTML5 lately (thanks to Steve Jobs), but surprisingly few people actually know how and when to use HTML5 tags. Obviously one of the most talked about addition to HTML5 is the audio tag.

Here is a basic audio tag implementation:

<audio id="player" name="player" src="song.mp3" controls="controls">
</audio>

Simple and elegant right? Not really.

The Problem

Every browser has it’s own way of displaying the controls. If you look at the music player on safari, you’ll see a Quicktime player. If you look at it on Firefox, you’ll have a completely different look, same goes for other browsers including the iPad and iPhone.

The Solution

There is of course a solution to all this: Make your own controls.

The audio tag, like any other html element, can be modified via javascript. In other words,  you can play, stop, pause and load audio files remotely with simple javascript methods.

Below is a simple example of how to use Javascript ( jQuery in this case ) to control music playback with an html5 audio tag.

 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
 
<script>
	$(document).ready(function(){
		$("#play-bt").click(function(){
			$("#audio-player")[0].play();
			$("#message").text("Music started");
		})
 
		$("#pause-bt").click(function(){
			$("#audio-player")[0].pause();
			$("#message").text("Music paused");
		})
 
		$("#stop-bt").click(function(){
			$("#audio-player")[0].pause();
			$("#audio-player")[0].currentTime = 0;
			$("#message").text("Music Stopped");
		})
	})
</script>
 
<audio id="audio-player" name="audio-player" src="song.mp3" ></audio>
<div id="message"></div>
<a id="play-bt" href="#">Play music</a> | <a id="pause-bt" href="#">Pause music</a> | <a id="stop-bt" href="#">Stop music</a>

This is obviously a very basic implementation of HTML5 music player controls but you get the idea.

Important Notes / considerations

When deciding whether to use flash or HTML5 audio in your projects, always consider the following:

  • Because of format licensing issues, you cannot play mp3 files in Opera and Firefox. In other words you will need to have all your audio files in both .ogg and .mp3 format in order for everyone to enjoy it.
  • HTML5 penetration rate is still very low and will take years to catch up to Flash.
  • As you probably know, Flash is not compatible on the iPhone / iPad / iPod, so HTML5 has the advantage here.

More posts on HTML5 coming soon.