简体   繁体   中英

save how much of the video has been played

I currently try to find out how much of a video has been watched and played and at a certain point I would like to trigger a function.

The problem I occur is that I don't know how to keep track of how much has been watched. For example if you watched 30 seconds and rewind for 10, then you essentially watched 30 seconds and not 20, which currentTime would display.

 const video = document.getElementById("video"); const set = new Set(); const percent = .8; let toWatch; function mediaWatched (curr) { alert(`${curr}% of media watched`) } function handleMetadata(e) { toWatch = Math.ceil(video.duration * percent); console.log(toWatch, video.duration); } function handleTimeupdate (e) { set.add(Math.ceil(video.currentTime)); let watched = Array.from(set).pop(); if (set.has(toWatch) && watched === toWatch) { video.removeEventListener("timeupdate", handleTimeupdate); console.log(watched); mediaWatched( Math.round(watched / Math.ceil(video.duration) * 100) ); } } video.addEventListener("loadedmetadata", handleMetadata); video.addEventListener("timeupdate", handleTimeupdate);
 <video width="400" height="300" controls="true" poster="" id="video"> <source type="video/mp4" src="http://www.sample-videos.com/video/mp4/720/big_buck_bunny_720p_2mb.mp4" /> </video>

How can I add such behavior to trigger a function that if 80 percent has been watched and has at least been played?

Thanks so much!

So what you're saying is if a user ever hits a marker then you want to do something? So if they ever hit 80% of the way through the video then you want to do something? If that is the case, just check on each timeupdate and once they hit the marker do something. If they ever go past the marker and rewind, it won't matter (just make sure to guard against doing your action again if thats not what you want.)

If what you're saying is you want to check if the user has been watching the video for a certain time, as opposed to how much of the video they have watched. Then just use a setInterval to keep track of how long they have watched for.

const timer = setInterval(() => {
  videoWatchedFor += 1;

  if (videoWatchedFor === someTime) {
    //doSomething;
  }

}, 1000);

Here is how I do it

  const getPlayedTime = (player) => {
    let totalPlayed = 0;
    let played = player.played;

    for (let i = 0; i < played.length; i++) {
      totalPlayed += played.end(i) - played.start(i);
    }

    return {
      total: totalPlayed,
      percent: (totalPlayed / player.duration) * 100,
    };
  };
player.addEventListener("timeupdate", () => {
    const timeWatched = getPlayedTime(player);
    console.log(timeWatched);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM