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. It is very buggy but I do like these ideas for “open audio and video.” Same with images, but many sites will probably stick with flash since you can hide your mp3 source file (no music snitching). I’m more interested about video than audio since it’s fairly easy to play songs, however I see its use especially for band sites and such. MP3 should be supported though, along with a stop function but I think it’ll get better along the way.

    Micorosft will support it in 2022, nice one but too bad it’s probably true.

    http://www.myunv.com

  2. In responce to last comment, Can you “really hide your mp3” using flash? Tell me how?

  3. for the close tab bug (music not stoping after tab closed) maybe their could be a work around using the window.onunload event to destroy the audio tag, or if it doesn’t work, at least pause it

  4. for stop function, you can use a modified version of your load one..

    you make a var “song” who is = the input file to load on load function, and for stop it, just load it without play 😀

    (sorry for my bad english, i’m french )

  5. I stream my audio using PHP on Ubuntu. Try this:

    session_write_close(); //otherwise the $_SESSION is LOCKED while streaming

    header(“Content-Type:audio/ogg”);
    $cmd = “mpg123 -q -s \””.$file.”\” 2>/dev/null | oggenc -q 7 –quiet –raw-chan=2 -“;
    passthru($cmd);

  6. The jquery nonsense also made the example files basically worthless to me as well.

    I wanted to see html and javascript… not additional dependencies with their own syntax outside of what I want.

    🙁

  7. anon: Just add id’s to the tags and then do document.getElementById(). At the same time I highly recommend looking at JQuery. It will save you much work in the long run.

  8. thanks so much! i was looking/waiting for this level of functionality for a long time!
    incidentally,
    function stop(el) {
    el.pause();
    el.currentTime = 0;
    }
    (sorry, that is clunky, but you know, you can add a stop method to the object this easily)
    the big thing to me, aside from scriptable repositioning, is multi-track playback (multiple elements can play simultaneously – in ffox at least, currently)
    also, incidentally, hopefully we can look forward to this becoming part of the spec: https://bugzilla.mozilla.org/show_bug.cgi?id=490705
    cheers

  9. sorry
    i couldn’t post my html tags in previous 2 posts.

    in response to folks who got confused by jquery, just use the following tag in your html file and put the ring.wav or whichever *.wav file in the same folder.

    < audio src=”ring.wav” controls=”controls”>

    it worked for me. i am a novice.

  10. I’m using a lot of HTML5 code, and audio is one of the tags I’ve got a lot of experience using. You say MP3 isn’t supported, but that’s far from the truth. Some browsers ONLY support MP3. What I ended up doing is dual encoding all my audio and sound as both .mp3 and .ogg, and set the inner html of this tag to include both as source items. Some browsers will pick up the ogg source, while others will skip over to the mp3 source. Expect to have to do this for some time until the powers at be decide to stop bickering over file format.

  11. Thanks. Great article and comment…

    “Microsoft will probably implement the audio and video tag in 2022.”

    Unfortunately, I think you’re probably right about that date. 😉

  12. You know what, it’s very easy to “stop” the sound.
    Like this:

    function stopsound(){
    audioElement.pause();
    audioElement.src=audioElement.src
    }

  13. For those of us who don’t want to learn JQuery, can someone translate this into JS?

    from the “Load a sound” example…

    audioElement.addEventListener(“load”, function() {
    audioElement.play();
    $(“.duration span”).html(audioElement.duration);
    $(“.filename span”).html(audioElement.src);
    }, true);

    also, can you explain what the play() is doing there?
    I thought we were just loading it.

    Thanks

  14. Just tested with Internet Explorer 9
    Audio tag is working with playback controls, though it only supports mp3 format.

    Seems your estimate of 2022 was way off.

  15. Well at the time, I did not know that Microsoft would finally decide to get into the game with ie9 😉

  16. Pingback: Música en HTML5
  17. I would like to add a function Autoplaying has opened the page, is it possible? how do I do?

  18. How could I use the HTML audio tag to play audio when a button of my choice is clicked. For example I have a play button icon, and I want to be able to play audio if that is clicked…

  19. Good article. Does anyone know how to make the audio go back to the start and stop with one command in javascript, if this is even possible?

    1. John:

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

      Cedric Dugas: Thank you, VERY MUCH!!

  20. ” you cannot modify the player style “, actually, some basic style can be modify by CSS
    such as: width,height,color,background-color, but i am sure there are different display in different browser

Comments are closed.