mpdc
mpdc

Reputation: 3560

Firing off an AJAX request on audio play

I'm looking for the best way in which to log that an embedded audio file within a page is played. My first instinct is to try and fire off an AJAX request whenever the Play button is pressed.

I'm looking at the Media Events docs, and believe that the playing event is the one I'm after. Is this correct? I'm also worried it might fire off AJAX requests every time the play button is pressed and not just the first time (if they pause and unpause, for instance) and this might give skewed logs.

This is the listener example the documents give for media events:

var v = document.getElementsByTagName("video")[0];
v.addEventListener("seeked", function() { v.play(); }, true);
v.currentTime = 10.0;

But how could I integrate this in to the following code:

<audio id="123" controls>
    <source src="../uploads/filename.mp3" type="audio/mpeg">
</audio>

I have attempted the following, but nothing seems to be happening:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $('audio').each(function() {
            var id = $(this).attr('id');
            $(this).addEventListener("playing", function() {
                alert(id);
            });
        });
    });
</script>

Upvotes: 0

Views: 546

Answers (2)

Dipiks
Dipiks

Reputation: 3928

About the events:

The play event occurs when the audio/video has been started or is no longer > paused.

The playing event occurs when the audio/video is playing after having been paused or stopped for buffering.

You can read more on this answer

And for firing an event only one time ou can use the .one() function of jquery:

.one( events [, data ], handler )

Description:

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

Like:

$(this).one("playing", function() {
    alert(id);
});

Upvotes: 2

Dan Nagle
Dan Nagle

Reputation: 5425

The 'playing' event is fired when ever the media playback starts, resumes or is restarted.

The easiest way to ensure that the event is only handled once is to remove the event listener in the event handler function.

function oneTimeEventHandler(e) {
  // remove this handler
  e.target.removeEventListener(e.type, arguments.callee);
  // now handle the event
  alert("This event will only be handled once!");
}

Example on CodePen: http://codepen.io/anon/pen/mRErLR

Upvotes: 1

Related Questions