Get User watched total time of a video in jwplayer

2k Views Asked by At

I want to capture Total Played/watched time of a video from jwplayer. using below sample code.

jwplayer("player").setup({
    "playlist": [
        {
            "sources": [
                {
                    "default": false,
                    "file": 'https://content.jwplatform.com/manifests/yp34SRmf.m3u8',
                    "label": "0",
                    "type": "hls",
                    "preload": "meta"
                }
            ]
        }
    ],
    "height": "240",
    "width": "100%",
    "aspectratio": "16:9",
    "stretching": "uniform",
    "controls": true,
    "autostart": true
});

jwplayer("player").on('time', function (e) {
    var count = this.getPosition();        
});

Could you please help me doing this.

3

There are 3 best solutions below

2
boyntoni On BEST ANSWER

The best way would be to rely on the JW Player events for this, specifically the on('time') event.

let totalTimeWatched = 0;
let previousPosition = 0;
jwplayer().on('time', (e) => {
    const { position } = e;
    totalTimeWatched += (position - previousPosition);
    previousPosition = position;
});

If you do want to count time for ads, as well, you can use the adTime event, which has also has a position property.

EDIT

To account for seeking behavior you can use an additional listener, on('seek') to reset the previousPosition. See below:

let totalTimeWatched = 0;
let previousPosition = 0;
jwplayer().on('time', (e) => {
    const { position } = e;
    totalTimeWatched += (position - previousPosition);
    previousPosition = position;
});

jwplayer().on('seek', (e) => {
    previousPosition = e.offset;
});
0
Cerlin On

You can get the total number of milliseconds the video is played by this simple logic

// In ms
var totalPlayBackTime = 0

setInterval(
    function() {
        if(player.getState() == "playing") {
            totalPlayBackTime = totalPlayBackTime + 500
        }
    },
    500
);

Here the code will be executed every 500 ms to check if the player is playing. If it is, add 500 ms to the total playback time. Read the totalPlayBackTime variable to get the playback time.

This way you don't have to rely on jwplayer events

NOTE: I haven't tested this with ads.

1
Niels On

Why dont you use e.currentTime?