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.

68 thoughts on “Introduction to the HTML5 audio tag javascript manipulation

    1. 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—–

  1. 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

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

  3. 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.

    1. 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?

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

    be working as a future stop method?

  5. 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 ?

  6. 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..

  7. 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.

  8. For stop
    you can give like following code..

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

Comments are closed.