TheThirdMan TheThirdMan - 4 years ago 129
jQuery Question

Execute Javascript code 5 seconds before html5 audio element reaches end of playback

I'm working with a default

element that I'm interacting with through jQuery (changing source, playing/pausing - the usual). Now I'm trying to fade into the next track (of a second audio element), starting it 5 seconds early to have a seamless transition.

From what I gathered from the media events and audio element attributes pages, no method exists to do this by default - the closest thing in existence seem to be the
event (which fires too late, obviously), and the
attribute, which has the same problem.

I seperated my previous attempt into an answer to remove the question from the unanswered queue, but it originally was included here

Any help on solving this problem more efficiently, natively in a way I missed, or improving on my existing solution are greatly apprechiated! Thanks in advance.

Answer Source

At this point, the only solution I see is to check the duration of the track ahead of time, then set the following timeout:

$('audio').bind('loadedmetadata', function() {
  duration = $(this).prop('duration') * 1000; // get duration in milliseconds
  var fadetimer = setTimeout(function(){
    // set up next audio file
  }, duration - 5000); // execute timeout 5 seconds before end of playback

This seems vastly inefficient to me, however. I am also unsure whether this method will leave "garbage" timeouts or event bindings running in the background, which will eventually add up and slow down the application.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download