I\'d like to start and stop HTML5 playback in a random position with fade in and fade out periods to smooth the listening experience.
What kind of mechanisms exists
Old question but if anyone is looking for a vanilla JS way to do this I just wrote something up for project and thought I'd post it here since my search for a solution was in vain. If you are already working with a video or audio element, there's a good chance you don't really need to use jQuery to control the object anyways.
function getSoundAndFadeAudio (audiosnippetId) {
var sound = document.getElementById(audiosnippetId);
// Set the point in playback that fadeout begins. This is for a 2 second fade out.
var fadePoint = sound.duration - 2;
var fadeAudio = setInterval(function () {
// Only fade if past the fade out point or not at zero already
if ((sound.currentTime >= fadePoint) && (sound.volume != 0.0)) {
sound.volume -= 0.1;
}
// When volume at zero stop all the intervalling
if (sound.volume === 0.0) {
clearInterval(fadeAudio);
}
}, 200);
}
This version doesn't allow for editing the fadeout time (set to 2 seconds) but you could pretty easily argumentize it. To fully generisize this, extra logic would be needed to also first check what the volume was set to in order to know the factor by which to fade it out. In our case, we preset the volume to 1 already and browser volume control is out of the users hands as it's for a slideshow thing so it wasn't needed.
To get to a specific part of the audio you'd want to check the seekable timerange and just set the currentTime randomly based on what's available.