Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you detect if an HTML5 audio tag has been listened to for at least x seconds?

Tags:

html

audio

I'd like to log when users listen to an audio element for more than 5 seconds. How can I detect this with HTML5?

like image 286
dan Avatar asked Aug 08 '11 19:08

dan


1 Answers

I would handle the play event, and then use a setTimeout call track when they're done. Something like this (pseudo code):

    var timeHandler = null;

// if they stop listening, don't give them the alert
   myAudioElement.addEventListener('stop', function() {
     if (timeHandler) clearTimeout(timeHandle);
   });

// when they start to play, set an event to pop up 5 seconds later
    myAudioElement.addEventListener('play', function() {
        timeHandler = setTimeout(5000,function() {
          // here I would make some kind of ajax call to log the event
          alert("it's been 5 seconds!");
        });

As always, this could get far more complex depending upon your needs. You could also just use the ontimeupdate event to track where the playhead is currently sitting. For a reference on html5 audio events, check out this page:

https://developer.mozilla.org/en/DOM/Media_events

Good luck!

like image 158
Justin Beckwith Avatar answered Nov 07 '22 22:11

Justin Beckwith