Setting HTML5 audio position

katspaugh picture katspaugh · Mar 5, 2012 · Viewed 90.2k times · Source

How to jump to certain time offsets in HTML5 Audio elements?

They say you can simply set their currentTime property (emphasis mine):

The currentTime attribute must, on getting, return the current playback position, expressed in seconds. On setting, if the media element has a current media controller, then it must throw an INVALID_STATE_ERR exception; otherwise, the user agent must seek to the new value (which might raise an exception).

Alas, it doesn't seem to work (I need it in Chrome).

There are similar questions, although, no answers.

Answer

katspaugh picture katspaugh · Mar 5, 2012

To jump around an audio file, your server must be configured properly.

The client sends byte range requests to seek and play certain regions of a file, so the server must response adequately:

In order to support seeking and playing back regions of the media that aren't yet downloaded, Gecko uses HTTP 1.1 byte-range requests to retrieve the media from the seek target position. In addition, if you don't serve X-Content-Duration headers, Gecko uses byte-range requests to seek to the end of the media (assuming you serve the Content-Length header) in order to determine the duration of the media.

Then, if the server responses to byte range requests correctly, you can set the position of audio via currentTime:

audio.currentTime = 30;

See MDN's Configuring servers for Ogg media (the same applies for other formats, actually).

Also, see Configuring web servers for HTML5 Ogg video and audio.