ethrbunny
ethrbunny

Reputation: 10469

HTML5 video - measuring playback

Is it possible to measure viewing time for the 'video' tag? I see that it has 'onplaying' and 'onpause' events so I could probably fake a timer.

Just wondering if there is something more that Im missing.

Upvotes: 1

Views: 285

Answers (3)

user3426391
user3426391

Reputation: 38

I tried to accomplish the same thing in a project I'm working on. I did it using a jquery stopwatch plugin.

This is the JS you'll need:

var w = new Stopwatch();

document.querySelector("#video").addEventListener("playing", Start, false);
document.querySelector("#video").addEventListener("pause", Stop, false);
document.querySelector("#video").addEventListener("waiting", Stop, false);

function Start() {
    if ($("#video").get(0).paused == true)
        Stop();
    else
        w.start();
}

function Stop() {
    w.stop();
}

And this is how you get the elapsed view time (in milliseconds):

var e = w.getElapsed();
time = (((e.hours * 3600) + (e.minutes * 60) + e.seconds) * 1000 + e.milliseconds); // Total view time

Keep in mind - this is not the most accurate way to do this, yet it is the best I've managed to accomplish with my coding skills.

Good luck!

Upvotes: 0

Joshua Dwire
Joshua Dwire

Reputation: 5443

HTML5 media elements fire a 'timeupdate' event. See http://dev.w3.org/html5/spec/media-elements.html#event-mediacontroller-timeupdate. When that event fires, you can check .currentTime for the current time and .duration for the length of the video. It also fires a 'durationchange' event.

Full HTML5 Media DOM Interface Specs: http://dev.w3.org/html5/spec/media-elements.html

Upvotes: 1

Adam
Adam

Reputation: 44929

videoElement.currentTime

Try it on jsFiddle!

Source: https://developer.mozilla.org/en-US/docs/DOM/HTMLMediaElement

Upvotes: 0

Related Questions