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!
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
you can use this automatically or manually depending on your needs:
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>
var myAudioElement = document.getElementsByTagName("audio")[0]; // get your audio element
myAudioElement.saveSession = true; // activate AudioSession
myAudioElement.saveSession = false; // deactivate AudioSession
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 elementsessionCleared
is fired when the the session key has been removed from storagesessionSaveActivated
is fired when AudioSession has been activatedsessionSaveDeActivated
is fired when AudioSession has been deactivated
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
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
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.
- check compatibility with popular polyfills
- add tests
- annotate source
- apply functions to HTMLMediaElement therefore supporting both Audio and Video(?)
- Upfront Podcast for the demo audio files
- Ben and Daryl for input on JS Best Practices
MIT, see the file for details