Wednesday, 19 September 2012

currentTime not working with the HTML5 Audio tag.. a solution!

Today I've been using the HTML5 Audio tag (in fact actually just the JavaScript Audio() object). I ran into a number of issues where clearly-documented functions simply didn't work.

Here's some sample code, with XXXXs marking what wasn't working for me (in any browser).

Now it turns out the reason these functions didn't work is not that browsers suck and this whole HTML5 is hugely overrated (my initial reaction), but was in fact that the server serving the MP3 files did not support streaming. Of course if would have been nice if somehow the audio object would warn me about this rather than sitting there doing nothing, but you can't have everything.

Anyway, now the question was how do I make my server support streaming? Do I need to sign up for some kind of premium service? Or spend weeks implementing a streaming sever?

Thankfully not. It turns out you 'simply' need to make your server support HTTP Range requests. If your server uses PHP, you're in luck. I've got a complete working example which I can share with you right now.

Note I did not write this code, I found it here and added it to gist for posterity.

Simply add this code to your PHP server, and when you're about to serve an MP3 (or OGG or whatever) call this function.

For reference, I call the function like this (where $fullPath is the absolute path to my MP3 Resource).

smartReadFile($fullPath, basename($fullPath), 'audio/mpeg, audio/x-mpeg, audio/x-mpeg-3, audio/mpeg3');


  1. You sir... are a badass. That script is freaking awesome. Solved my issues. Thanks so much!


  2. I have encountered an issue with setting currentTime but I don't think it has to do with streaming because I preload the sound file first. My problem seems to be related to contexts. I start the Audio object from the window but when I try changing the value from XMLHttpRequest response it does NOT work.

    Have you seen anything similar? my issue is posted below.

  3. Man, this post made my day at work. I'm working with a tool at the callcenter I work to and the server (in Lua) was not serving the mp3s correctly. Thanks to this headers that you showed I can now skip some parts of the audio and play correctly in the browser.


  4. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this websites uk

  5. Thank you very much! Works perfect!

  6. You save my day ! thx a lot :)

  7. An astounding web diary I visit this blog, it's inconceivably magnificent. Strangely, in this current blog's substance made point of fact and sensible. The substance of information is instructive.
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training