/MediaSession

keep track of the position in html5 media elements and restore them on the next visit

Primary LanguageJavaScript

AudioSession

we all have been there: you are listening to a podcast on a website and you accidentally close the tab. You can reopen the tab, but if you didn't pay close attention to the timer, finding the right place again can be tricky. AudioSession is here to fix just that!

What is it?

AudioSession is an extension of the HTMLAudioElement prototype that keeps track of <audio> currentTime and saves it to localStorage to be able to retrieve it on the next play, regardless of page reload. Works great with autoplay [autoplay doesn't work crossbrowser and is under investigation #2] and has no issues with loop

Usage

you can use this automatically or manually depending on your needs:

Automatic activation

add save-session to your <audio> element like this:

<audio controls save-session>
      <source src="source.mp3" type="audio/mpeg" />
      <source src="source.ogg" type="audio/ogg" />
</audio>

JavaScript activation

  var myAudioElement = document.getElementsByTagName("audio")[0]; // get your audio element
  myAudioElement.saveSession = true; // activate AudioSession
  myAudioElement.saveSession = false; // deactivate AudioSession

Custom Events

for better integration in your project, AudioSession provides a set of custom events triggered at various points:

  • sessionStored is fired when the current position has been stored (fires often)
  • sessionRestored is fired when the stored position has been applied to the audio element
  • sessionCleared is fired when the the session key has been removed from storage
  • sessionSaveActivated is fired when AudioSession has been activated
  • sessionSaveDeActivated is fired when AudioSession has been deactivated

Browser Support

as AudioSession relies on Audio and localStorage, only browsers that implement these specs are supported

in development AudioSession has been tested on:

  • Chrome 25
  • Firefox 19

Limitations

HTML 5 Validation

as described in the Usage Section, AudioSession can be activated using the element property save-session. If you are keen on spotless validation, rename all instances of save-session to data-save-session

Session Key

The Session Key is build from the source URL of the file, this has the side effect that if you have the same audio file on multiple sub-pages it continues from where it left of.

It's either a bug or a feature depends on how you see it. You can use this side effect to keep music continuing, when going to the next page. If you don't want this to happen, use a unique ID for each <audio> element, and a include it in the sessionKey.

Further Plans

  • check compatibility with popular polyfills
  • add tests
  • annotate source
  • apply functions to HTMLMediaElement therefore supporting both Audio and Video(?)

Thanks to

License

MIT, see the file for details