MediaElement.js: How can I get percentage of time played (ej. 90%) in order count a complete visioned video

StackOverflow https://stackoverflow.com/questions/18559995

  •  27-06-2022
  •  | 
  •  

Pergunta

I need count the number of times has seen a video, but when reach 90%.

So, how can I get this percentage or read the total time and viewed time.

Thanks in advance, and have a nice day.

Foi útil?

Solução

Here is some working code, in this example I save the number of times a video is watched to localstorage.

(function($) {
    $(document).ready(function() {
        $('video').mediaelementplayer({
            success: function (mediaElement, domObject, player) {
                var duration;
                var player_counted = false;
                var i = 0;

                //lets see that it works!
                console.log(localStorage[domObject.src+'_times_watched']);

                //after metadata is loaded we can access the duration
                mediaElement.addEventListener('loadedmetadata', function(e) {
                    duration = mediaElement.duration;
                });

                //check if video is seen (above 90%) and increase times watched counter
                mediaElement.addEventListener('timeupdate', function(e) {
                    if((mediaElement.currentTime / duration) >= 0.9) {
                        if(!player_counted) {
                            if (localStorage.getItem(domObject.src+'_times_watched') !== null) {
                                i = parseFloat(localStorage[domObject.src+'_times_watched']);
                            }
                            localStorage[domObject.src+'_times_watched'] = ++i;
                            player_counted = true;
                        }
                    }
                }, false);
            }
        });
    });
})(jQuery);

If you don't want to use localstorage, replace it - and save to cookie/db or whatever you need.

If you do decide to use localstorage - you might also want to check for localstorage support, I use Modernizr if (Modernizr.localstorage) { look at modernizr source or search SO if you don't use modernizr.

If you have access to some unique identifier (ie: login id/e-mail) for each user watching the videos, make sure to add that before domObject.src+'_times_watched' to ensure correct counting for multiple users on the same browsers.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top