How to pause a video after a certain time? video.js - javascript

I've been messing with video.js whilst learning javascript but can't seem to figure out how to make the video pause after a certain time has passed.
myPlayer.play(function(){
whereYouAt = myPlayer.currentTime();
if (whereYouAt == 10) {
myPlayer.pause();
}
})
That is my pause code.

Check the currentTime in the timeupdate event callback:
var pausetime = 2; // stop at 2 seconds
var myPlayer = videojs('example_video_1');
myPlayer.on('timeupdate', function(e) {
if (myPlayer.currentTime() >= pausetime) {
myPlayer.pause();
}
});
myPlayer.play();
JSFiddle demo: http://jsfiddle.net/EdjxN/17/

Related

Javascript Play Video on Mouse Hover (Multiple Videos)

I have the following JavaScript code that work great when I hover over a video. I like how the start and stop is broken into functions and it allows me to customize the hover play exactly how I want. However, this code only works on the first video on the page and I have several videos that are loaded on the page dynamically.
I would like to modify this code so that it will work on all videos on the page. I'm thinking that maybe the functions need to be called inside a loop? I'm not sure as I do not know JavaScript well, so any help on how to modify this code would would be much appreciated!
const video = document.querySelector("video");
function startPreview() {
video.muted = true;
video.currentTime = 5;
video.playbackRate = 2.5;
video.play();
}
function stopPreview() {
video.currentTime = 5;
video.playbackRate = 1;
video.pause();
}
let previewTimeout = null;
video.addEventListener("mouseenter", () => {
startPreview();
previewTimeout = setTimeout(stopPreview, 3000);
});
video.addEventListener("mouseleave", () => {
clearTimeout(previewTimeout);
previewTimeout = null;
stopPreview();
});
You can do event delegation to handle all videos. So:
document.body.addEventListener('mouseenter', (event) => {
if (event.target.matches('video') {
// start playing
}
});
More on the matches() method on MDN.
You would also modify the start and stop methods to take the video element as a parameter:
function startPreview(video) {
video.muted = true;
video.currentTime = 5;
video.playbackRate = 2.5;
video.play();
}
And pass them the event.target.

video.js - find the start time of a seek during playback

I am using video.js (http://www.videojs.com/) to build a video approval system and need to log user actions in the player. I can do this easily enough with play, pause, end etc. but have hit a problem when trying to log seeks.
I want to be able to log the start and end times of any seeks within the plaback, so we know if the user has not actually watched a section of the video. The player seems to offer events to support this, but I am struggling to get correct timings from it.
When the user skips through a video the player emits the following events in order: pause, seeking, seeked, play.
If I query the player object at any of these events using currentTime() the result is always the end time for the seek, even on the initial pause event. This means I can log where the seek ended but not where it started.
Can anyone help me to find the position in the video where the seek begins?
If this is not possible, I'd settle for a way to disable seeking during playback.
EDIT: adding code as requested. It's pretty simple:
var trackedPlayer = videojs('pvp-player');
trackedPlayer.on("play", function (e) {
console.log("Video playback started: " + trackedPlayer.currentTime());
});
trackedPlayer.on("pause", function (e) {
console.log("Video playback paused: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeking", function (e) {
console.log("Video seeking: " + trackedPlayer.currentTime());
});
trackedPlayer.on("seeked", function (e) {
console.log("Video seek ended: " + trackedPlayer.currentTime());
});
trackedPlayer.on("ended", function (e) {
console.log("Video playback ended.");
});
If I can get all the tracking I want I will replace console.log with ajax calls to store the data.
You can listen to timeupdate und take the next to last value you got there before seeking is called as your source:
var previousTime = 0;
var currentTime = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
console.log('seeking from', previousTime, 'to', currentTime, '; delta:', currentTime - previousTime);
});
This seems to work with the HTML5 tech. I have not tested with other techs.
There is, however, one glitch: the first time seeking a paused player yields only a small delta (and the almost-same previous value for both variables). But this shouldn’t matter much since the delta is only a few hundred milliseconds (and I gather you’re only interested in the “from” value).
Update
seeked is triggered far more infrequently than seeking. Try the following.
var previousTime = 0;
var currentTime = 0;
var seekStart = null;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = trackedPlayer.currentTime();
});
trackedPlayer.on('seeking', function() {
if(seekStart === null) {
seekStart = previousTime;
}
});
trackedPlayer.on('seeked', function() {
console.log('seeked from', seekStart, 'to', currentTime, '; delta:', currentTime - previousTime);
seekStart = null;
});
There are also many libraries for debouncing function calls (in this case the call to your backend).
I needed to find the same value for a project I was working on so I could determine whether or not a user was skipping forward or backward in a videojs player.
Initially, I thought to save the currentTime() a user was seeking from on timeupdate then immediately removing my timeupdate listener once seeking was dispatched. While this worked in some browsers like Chrome, unfortunately, I found that other browsers continued to fire timeupdate more frequently and would continue to update the currentTime() I was saving after the player actually seeked.
Here was the solution that ultimately worked across Safari/Chrome/Firefox. I have yet to test in IE.
var previousTime = 0,
currentTime = 0,
completeTime = 0,
position = 0;
trackedPlayer.on('timeupdate', function() {
previousTime = currentTime;
currentTime = Math.floor(player.currentTime());
// save 'position' so long as time is moving forward with each update
if (previousTime < currentTime) {
position = previousTime;
previousTime = currentTime;
}
});
// when seeking starts
trackedPlayer.on('seeking', function() {
player.off('timeupdate', onTimeUpdate);
player.one('seeked', onSeekComplete);
});
// when seeking completes
trackedPlayer.on('seeked', function() {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
});
I know this is an old post but this is the only solution that worked for me.
var counter = 0;
var beforeTimeChange = 0;
function handleSeeking() {
var timeoutTime = 300;
var beforeCounter = counter + 1;
if (trackedPlayer.cache_.currentTime === trackedPlayer.duration()) {
return;
// when video starts over, calls seek
}
beforeTimeChange = beforeTimeChange || trackedPlayer.cache_.currentTime;
setTimeout(function() {
if (beforeCounter === counter) {
console.log('before seek', beforeTimeChange, '\nafter seek', trackedPlayer.currentTime() - (timeoutTime / 1000));
counter = 0;
beforeTimeChange = 0;
}
}, timeoutTime);
counter++;
}
trackedPlayer.on('seeking', handleSeeking);
For a more accurate solution, you can listen to the events that trigger the seek such as mousedown on progress bar, left key, right key etc., and get the current time from these events.
For example in version 7.10.2 you can do the following,
let seekStartTime;
player.controlBar.progressControl.on('mousedown', () => seekStartTime = player.currentTime());
player.controlBar.progressControl.seekBar.on('mousedown', () => seekStartTime = player.currentTime());
player.on('keydown', (e) => {
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
seekStartTime = player.currentTime();
}
});
console.log(seekStartTime);
Note 1: There are two seperate mousedown event listeners for progress control and seek bar. This is because the video can be seeked by clicking outside the seek bar on the progress control as well.
Note 2: Seeking using hotkey numbers does not pause the video. However, if necessary you can add those keydown listeners too.
I needed to find the start and end of a seeking action in my project and I used #Motorcykey answer and it worked, but there was a small bug. when I tried to seek to a time before the current time while the player was paused, the position didn't get updated. so I added just one line and it fixed it. I've tried other solutions too but so far this was the best solution that I've found. Here's the code snippet on player 'seeked'
player.on('seeked', function () {
completeTime = Math.floor(player.currentTime());
console.log("User came from: " + position);
console.log("User ended at: " + completeTime);
position= Math.floor(player.currentTime())
});
Try with this code to know the length of video.
var duration = document.getElementById("duration");
var vid_duration = Math.round(document.getElementById("video").duration);
//alert(vid_duration);
duration.innerHTML = vid_duration;
//duration.firstChild.nodeValue = vid_duration;

Play few seconds of video onclick

Is there a way to play html video only for few seconds?
Currently when a user clicks on a table row the video seeks to a predefined time (highlighted below). So in the below example the video would seek to 7 seconds.
Is there a way to play the video from seconds onwards for just 10 seconds? i.e seek to 00:07 and play to 00:17 and stop?
Thanks
You can use timeupdate event along with currentTime attrribute
function playVideo() {
var starttime = 7; // start at 7 seconds
var endtime = 17; // stop at 17 seconds
var video = document.getElementById('yourVideoId');
video.addEventListener("timeupdate", function() {
if (this.currentTime >= endtime) {
this.pause();
}
}, false);
//suppose that video src has been already set properly
video.load();
video.play(); //must call this otherwise can't seek on some browsers, e.g. Firefox 4
try {
video.currentTime = starttime;
} catch (ex) {
//handle exceptions here
}
}
You could create a timer so after you "seek" the video, it will stop the video in 10 seconds.
so inside you seek function you would place.
var Video = $('Video Element')[0];
// After getting the video element play it.
Video.play();
// Now create a timer so in 10 second (1s = 1000 so 10s = 10000 ms) it will pause the video.
setTimeout(function(){
Video.pause();
},10000);
I made a small script which might help with this.
https://github.com/demux/jquery-video-cuepoints
Usage:
$(document).ready(function() {
var $v = $('#video');
$v.cuepoints({
17: function() {
$v[0].stop();
}
});
$('button').click(function(){
$v[0].play();
try {$v[0].currentTime = 7;} catch(e) {}
});
});

What HTML5 video event refers to the currentTime of the video being played?

I want the user to have the option to skip the preroll ad after a specified time (say 5 secs into the ad). Then the normal video would play. How can I achieve this? Currently I have something inline of this:
var adManager = function () {
var adSrc = url,
src = "http://media.w3.org/2010/05/sintel/trailer.mp4";
var adEnded = function () {
videoPlayer.removeEventListener("ended", adEnded, false);
videoPlayer.removeEventListener("playing", adPlaying, false);
$("#companionad").hide();
videoPlayer.src = src;
videoPlayer.load();
videoPlayer.play();
console.log(videoPlayer.currentTime);
};
var adPlaying = function () {
var companionad = $(responseXML).find("HTMLResource").text();
$("#companionad").html(companionad);
console.log(videoPlayer.currentTime);
}
return {
init: function () {
videoPlayer.src = adSrc;
videoPlayer.load();
videoPlayer.addEventListener("ended", adEnded, false);
videoPlayer.addEventListener("playing", adPlaying, false);
if (videoPlayer.currentTime > 5) {
$("#skip").show();
}
console.log(videoPlayer.currentTime);
}
};
}();
adManager.init();
What I am trying to do is:
if (videoPlayer.currentTime > 5) {
$("#skip").show();
}
show the skip button and continue to normal video. Is there any event that is continually fired as the video play progresses?
Do your check against the media.currentTime property in a handler for the timeupdate event. See documentation:
The timeupdate event is fired when the time indicated by the
currentTime attribute has been updated.
Just as an aside, this HTML5 video demo page is a really handy reference for playing around with the various properties and events available to you.

Stop video play when leaving a jquery mobile page

So I have a jquery mobile page with an html 5 video in it and that I want to be able to either stop playing and reset its self or just automatically pause the video. Would this be the correct javascript?
<script>
function restart() {
var video = document.getElementById("Video1");
video.currentTime = 0;}
if ($.mobile.activePage.attr('id') != 'a28') { "restart"}
</script>
have you tried the pagehide , it gets called when the current active page gets hide / changed.
$(function(){
$('#a28').live('pagehide',function(){
//stop the video
});
});
Make use of a loop, to check if the user is on the webpage. Store the time.
var lastSeen;
var loop = function (){
lastSeen = Date.now();
setTimeout(loop, 50);
};
loop();
var video = document.getElementById('Video1');
video.addEventListener('timeupdate', function (){
if(Date.now() - lastSeen > 100){
this.pause();
}
}, false);

Categories

Resources