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/
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.
useful. thanks for sharing.
Good article! Thanks!
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
In responce to last comment, Can you “really hide your mp3” using flash? Tell me how?
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
Always remember to set your load event listener before you call the load() method.
work on Google Chrome 3.0.195.1.
eK5kAN nnetnokagjdn
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 )
To stop de audio, just do this:
audioElement.pause();
audioElement.currentTime = 0;
sadly couldn’t make head or tail of the post as uses jquery which i dont get
Same here if you want to teach why use jqury
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);
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.
🙁
I don’t see the nonsense here, it is pretty simple to understand
Is there are version without the “$” ?
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.
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
Learning audio in html 5
Your browser does not support the audio element.
<!–
Learning audio in html 5
http://www.position-absolute.com/articles/introduction-to-the-html5-audio-tag-javas
cript-manipulation/
Your browser does not support the audio element.
–>
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.
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.
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. 😉
You know what, it’s very easy to “stop” the sound.
Like this:
function stopsound(){
audioElement.pause();
audioElement.src=audioElement.src
}
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
Thanks!
What band is that playing in your demo? That was an awesome song!
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.
Well at the time, I did not know that Microsoft would finally decide to get into the game with ie9 😉
and for the automatic reading how you made?
I would like to add a function Autoplaying has opened the page, is it possible? how do I do?
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…
Officially, you’re awesome!
Great article. Had problems with the volume control. The values are 0 – 1, not 50 as suggested above.
Mp3 Audio is supported, just not in Firefox.
Check the following link for a table of compatible formats.
http://w3schools.com/html5/html5_audio.asp
great.. i tried for the whole day for this type of control over html5 audio tag. obviously i failed. and finally at night i found this one. thanks a lot.
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?
John:
function stop()
{audioElement.pause();
audioElement.currentTime=0;
}
Cedric Dugas: Thank you, VERY MUCH!!
” 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
hi ,
i dont get the duration here, it is always NaN even if i set the source ?!
Thanks a lot!!! that’s exactly what i was looking for! 😀
nice tutorial
Work on IE9.
mp3 work too.
Thanks a lot for this topic. You saved my time.
How can I make it autoplay?
Thanks!