Introduction to the HTML5 audio tag javascript manipulation

by Cedric Dugas on July 12, 2009

Some of the new exciting features of HTML5 are the audio and video tag. This could potentially, in the long term, replace flash on the video level. I wanted to use the audio tag in one of my experiemental project, there is little information about how to manipulate the audio tag, and tought it would be great to have a starter guide.

One thing clear is this is still an early implementation, which also means it is a bit buggy. I had a strange bug where if I had a song playing and had javascript throw errors at the same time (not related together), I could not terminate the song. Closing the tab would not stop it, I had to restart Firefox. Which lead me to think that the process is still not completely linked only to the tab (in Firefox at least).

I used jquery in my demo because the application I developing is wrapped around it, but this is not necessary.

View demo
(Only consisting of 5 buttons)

What I learned

The API is somewhat easy to work with, as it should be, play(), pause(), want to stop the volume? audioElement.volume=0. Want to start playing at 55 seconds? audioElement.currentTime = 55. Pretty cool stuff.

The default html audio player controls are added automatically with a simple: controls=”true”, it has good and bad sides. You don’t have to worry about it, but at the same time, for now, you cannot modify the player style. Also when you right click you have a nice contextual menu where you can save the file in ff3.5.

A normal audio tag

Add and play a sound via JavaScript

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'loading.ogg');
audioElement.play();

Get the song filepath and duration

audioElement.src;
audioElement.duration;

Load a sound

var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Mogwai2009-04-29_acidjack_t16.ogg');
audioElement.load()
audioElement.addEventListener("load", function() { 
  audioElement.play(); 
  $(".duration span").html(audioElement.duration);
  $(".filename span").html(audioElement.src);
}, true);

Stop a song

audioElement.pause();

Change volume

audioElement.volume=0;

Play at exactly 35 seconds in the song

audioElement.currentTime=35;
audioElement.play();

The bad parts

No stop(), only pause(), I really do not know what stopped them to put stop() in the API.
No way to get the songs name.
The only accessible format are ogg and wav, no mp3 love. It also means that you will have to convert all your sounds in ogg.
As I said this is a bit buggy but understandable, the specs are not even finished.
Microsoft will probably implement the audio and video tag in 2022.

The good parts

The API is easy to use, you can have a song playing in no time.
You do not need to parse the audio object in the HTML body, you can have it played directly in your script.
In the end, I’m really happy on how this turned out.

Download the source code View demo

Tested on:
Firefox 3.5

Ressources

http://hacks.mozilla.org/2009/06/exploring-music-audio/
https://developer.mozilla.org/en/Using_audio_and_video_in_Firefox
http://webkit.org/blog/140/html5-media-support/

Ads
Sign up for testking E20-322 online classes to learn the latest skills in web development. Get complete information on htlm features and functions using testking 646-276 html toturials and testking NS0-163 study guide.



69 comments

Also, it’s not working in IE for me. It’s perfect in all other browsers. Any suggestions? Thanks!

by Tippie on February 10, 2012 at 4:12 pm. Reply #

Simple!
Step 1:
create a new audio object.

audio = $(”, {
‘loop’ : ‘loop’,
‘autoplay’ : ‘autoplay’
});

Step 2:
Than check if it can play mp3 by doing

(audio[0].canPlayType(‘audio/mpeg’)

or for ogg

(audio[0].canPlayType(‘audio/ogg’)

Step 3:
If it can play mp3 than load the mp3, or ogg than load ogg

final code

——beginCode—-
audio = $(”, {
‘loop’ : ‘loop’,
‘autoplay’ : ‘autoplay’
});

if (audio[0].canPlayType(‘audio/mpeg’)){
$(”, {
’src’ : ‘/audio/le.mp3′,
‘type’ : ‘audio/mpeg’
}).appendTo(audio);
}
if (audio[0].canPlayType(‘audio/ogg’)){
$(”, {
’src’ : ‘/audio/le.og’,
‘type’ : ‘audio/mpeg’
}).appendTo(audio);
}
—– endOfCode—–

by Aras on February 13, 2012 at 4:56 am. Reply #

Hi, the tag is working fine in Firefox for me, but on Windows the player controls look like “falling” downwards some 20 pixels after pressing play, and this causes troubles with pressing pause afterwards, because the button position is not recognised apparently. How could one make the controls stay in the same position, like it happens in Safari or Chrome, or even in Firefox on Mac OS X ?
Thank you

by nicola on February 15, 2012 at 7:00 am. Reply #

Hello! Nice article! just one question:
What is the song you are playing in the demo? it’s quite cool!

by Gerry on March 12, 2012 at 12:15 pm. Reply #

SoundHound tells me it’s ‘Glasgow Mega Snake’ by Mogwai. :)

by Qyzbud on June 11, 2012 at 7:43 pm. Reply #

wow , nice ! it’s very useful for me

by 痞子 on March 29, 2012 at 11:07 pm. Reply #

I downloaded the audiotag provided by Cedric and copied it to my website. The page is loaded like in the Demo, but the difference is that I don’t hear anything at my site. I use Firefox 6 in my Windows 7 laptop.

by Jun on March 31, 2012 at 8:14 am. Reply #

The problem seems to be at my Goddady hosting web site. I copied audiotag to my personal web site and it works. Goddady doesn’t support java script?

by Jun on March 31, 2012 at 8:32 am. Reply #

Wouldn’t a simple
Audio.prototype.stop=function(){
this.pause();
this.currentTime=0;
}

be working as a future stop method?

by Macke on April 5, 2012 at 8:21 am. Reply #

i do it like this:

function playsound()
{
var audioElement = document.getElementById(‘alarm’);
audioElement.play();
}
but “document.getElementById(‘alarm’)” selector, kills jquery selectors

if i use jquery selector like this:

function playsound()
{
var audioElement = $(‘#alarm’);
audioElement.play();
}
or

function playsound()
{
$(‘#alarm’).play();
}

then it’s don’t work :/

how can i use it with jquery selectors ?

by MuratHan on May 26, 2012 at 5:54 pm. Reply #

i found..
selector: $(“#audio”)[0]

functions:

function togglesound()
{
if($(“#audio”)[0].paused)
{
$(“#audio”)[0].play();
}else
{
$(“#audio”)[0].pause();
}
}

function stopsound()
{
if($(“#audio”)[0].played)
{
$(“#audio”)[0].pause();
$(“#audio”)[0].currentTime=0;
}
}

thanks for article..

by MuratHan on May 26, 2012 at 6:46 pm. Reply #

Thanks, this really helped me out.
Here’s the code to stop the track:
function stop() {
document.getElementById(“audio”).currentTime=0;
document.getElementById(“audio”).pause();
}
It’s very simple, I know, but I just thought i’d share it.

by Daniel on October 9, 2012 at 10:51 am. Reply #

Nice work . It got me started on audio tags. i’m just curious that whether audio tag have load method or not . because the demo’s duration never shown up for me .. and it did when i changed the load to canplaythrough .. https://developer.mozilla.org/en-US/docs/DOM/Media_events

by arun on November 1, 2012 at 7:42 am. Reply #

Hi, only firefox and opera dont support mp3 files on js player. All the others allow mp3.

by Claudio on March 21, 2013 at 12:40 am. Reply #

For stop
you can give like following code..

function stop()
{
myaudio.pause();
myaudio.currentTime = 0;
}

by Jitendra Raj (B.Tech) on June 19, 2013 at 6:25 am. Reply #

Nice article, thanks!

by amenciones on April 21, 2014 at 12:00 pm. Reply #

Leave your comment

Required.

Required. Not published.

If you have one.