use handleSeeked() function in videojs - javascript

I'm using videojs to play videos on the site and I'm trying to create log on video streams but I have difficulty logging users seeking in videos. I need seek start and end time and it seems that the built in handleSeeked() function in videojs does the job but I can't get it to work. Does anybody know how to use this function?
Update
It seems that this question is about the same problem but the solutions aren't fully working and each one has a little problem.

I was able to get what I wanted with the following code but I had to handle everything on my own so if there's still a better way to do this I'd be happy if you could help me.
var previousTime = 0,
currentTime = 0,
completeTime = 0,
position = 0;
player.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;
console.log('pos',position)
previousTime = currentTime;
console.log('pre',previousTime)
}
});
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())
});

Related

How to update a web page in reaction to a push-notification?

I am exploring the world of push-notifications in Node.js and have one question.
Following a few tutorials, I now have a small app firing a few notifications and those pop up in my web browser as expected.
Here is the question:
Instead of having a notification popping up, would it be possible to have a field in my web page updated?
(For example: a clock or a counter)
If the answer is YES, how can I do it? Do I need to change the service worker? The client? Or what?
Here is the current code:
const SECS = 5 * 1000;
let rankVal = 0, counterVal = 1;
const notificationLoop = setInterval(() => {
let currentDate = new Date(),
timeLag = (currentDate-referDate)/1000
const payload = JSON.stringify({
title:'Event is reached!',
timeLag:timeLag.toString()
});
webPush.sendNotification(subscription,payload).catch(err => console.error(err));
console.log('-- setInterval --' + counterVal + ' : ' + rankVal);
if (counterVal>262144) {clearInterval(notificationLoop);}
rankVal += 1
counterVal *= 2
}, SECS);
Check out pusher, should do exactly what you want:
https://pusher.com
Note, you can use pusher for popups and stuff aswell, but mainly it is really good for keeping track of fields and changing data if someone else is using the site at the same time, etc.

function increment sync with video (or auto increment)

I'm busy with a webdoc that I'm partially creating on hype, the video are hosted on vimeo (so I need to use the vimeo api for some tasks like seekto) but my difficulties should be limited to js.
the objective is to display a given image at a given time interval of the video.
With my code below, I do get the string "test", "success" and "confirmed success" at the right time in my div id=popimgbox, and I can seek back and forth in the video and still get the right "answear", if I may say so.
Now, I have images that are all stored in the same folder, and all named popimgX.jpg, with X being a number.
I want
to store the URLs of my images in a variable let's say "popimgurl"
that my variable is updated (by a function???) in order to contain the URL of a given immage for a given interval of time of the video
to still be able seekto back and forth in the video and get the right URL at the right time
To do so I created a function increment, and a pair of variable. With the code below, my popimgurl variable is indeed updated once the video reach 3 seconds, but it do not increment only once... untill the video reach 6 seconds, when I want to update my popimgurl variable once again.
I tried to use for with js break and js closure but did not manage for some understandable reasons after thought;
I did quite some try with switch, but I'm stuck with the fact that the case must be string or single numerical value, not numerical interval or comparaison.
thank's in advance for your help :-)
var iframe = $('#vplayer_1')[0];
var player = $f(iframe);
var status = $('.status');
fired = 0;
//my try to sync increment
var dia = (function () {
var n = 0;
return function increment() {return n += 1;}
})();
function dian(){
popimgurl = '${resourcesFolderName}/popimg'+ dia() +'.jpg';
popimgloader = '<img src ="' + popimgurl + '">';
}
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
status.text('ready');
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
// Call the API when a button is pressed
$('button').bind('click', function() {
player.api($(this).text().toLowerCase());
});
function onPause(id) {
status.text('paused');
}
function onFinish(id) {
status.text('finished');
}
function onPlayProgress(data, id) {
status.text(data.seconds + 's played');
//my chapters, when I want the img to change within popimgbox
if (data.seconds >= 1) {
popimgbox.innerHTML = "test";
}
if (data.seconds >= 3) {
// popimgbox.style.display = "success"
dian();
popimgbox.innerHTML = popimgurl;
}
if (data.seconds >= 6) {
// popimgbox.style.display = "confirmed success"
dian();
popimgbox.innerHTML = popimgurl;
}
}
PS1: disclamer, I'm a beginer coder, i do my best so excuse my french if my question isn't well formulated or if the answer is somewhere but I was unable to see/understand it
PS2 : i did quite a try with popcornjs, but not way to make it work with vimeoapi and within hype, quite frustrated ;-)
PS3: as this is my first post I would like to thank's you all for the great support available here; I owe you most ;-)
Finally I'll answer myself.
It's a solution that only stand for vimeo, as this is what I use to host my videos, but very little changes have to be done to work with the html5 <video> tag as well.
First you need to define your variables and your intervals:
var intervals =[11.56, 44.08, 115, 125, 127.92, 177.72];
var index;
Then you need to add an event listener timeupdate that return the elapsed time , filter intrevals according to the elapsed time data.seconds or seconds and define the value of index as the indexOf the last entry of your filtered array intervals
player.on('timeupdate', function(data) {
seconds = data.seconds;
index = intervals.indexOf(intervals.filter(function(nb) {
return seconds < nb;
})[0]);
if (diaIndex == -1) {
// do something if seconds > the higher value of your last interval
}
And that's it !
Now for
seconds = [0, 11.56[ --> index = 0
seconds = [11.56, 44.08[ --> index = 1
seconds = [44.08, 115[ --> index = 2
and so on
Now we can use index as a variable for instance to display a given image :
var imgNum = 0;
function diaplayImg(index) {
if(index === imgNum) {
return;
// this will avoid that the same image is releaded on every timeupdate events
}
else {
imgNum =+ index
document.getElementById('myImageWraper').innerHTML = "<img src='img" + imgNum+ ".png'>"
};
}
Don't forget, you need to call the function displayImage() in your timeupdate event listener, it will then be fired every ±250ms but the image won't be reloaded each time
PS : vimeo has realeased its new api between my question and my answer so the question use the old api while the answer use the new one

Why does a new audio file start playing if one is already playing? (JS)

I don't know why, but I can't figure out why this does not work. I've been sitting for hours trying different methods, reading and watching videos on the subject, but I still can not figure it out.
Q: Why does a "new" audio file start playing, overlapping the previous one, every time I click the element? Should my if statement not take care of that?
document.getElementById("chatWrapper").addEventListener("click", playSound);
function playSound() {
//alert("Success!");
var sEE0 = new Audio('../sound/00-menu-music.mp3');
sEE0.volume = 0.2;
if (sEE0.duration > 0) {
return;
} else {
sEE0.play();
}
}
How do I solve this?
Thanks in advance!
You seem to be creating a new audio element each time you click.
Try to initialize it only once: (attn, quick'n'dirty!)
document.getElementById("chatWrapper").addEventListener("click", playSound);
var sEE0 = new Audio('../sound/00-menu-music.mp3');
function playSound() {
//alert("Success!");
sEE0.volume = 0.2;
if (sEE0.duration > 0) {
return;
} else {
sEE0.play();
}
}
like #frontend_dev said, one of your problem is the variable scoping, other is you are checking using sEE0.duration, but that would give you the length of the audio file, which is bound to be bigger than 0, may be that's why it is not playing, what you are looking for is currentTime, the if condition should be if (sEE0.duration > 0) { ,
but I would prefer checking if the audio is playing or paused, rather than checking till what part the audio has played( unless the usecase requires that)
I would re-write the code as:
document.getElementById("chatWrapper").addEventListener("click", playSound);
var sEE0 = new Audio('../sound/00-menu-music.mp3');
sEE0.volume = 0.2;
function playSound() {
//alert("Success!");
if (sEE0.paused) {
sEE0.play();
}
}

Apple Dashboard Widget setTimeout Not Working

I'm working on a calendar based dashboard widget that I want to automatically updated at the start of a new day. However, I can't seem to get it to actually update. It seems to work fine running in a browser. I've also tried manually entering the setTimeout delay to something much shorter (like 1 or 2 minutes) and that seems to work.
This is the code I have:
function Calendar() {
var _self = this;
this.daytimer = null;
this.daytimerAction = function() {
_self.updateCurrentDate();
}
this.resetDaytimer();
}
Calendar.prototype.resetDaytimer = function() {
var today = new Date(),
tomorrow = new Date();
if (this.daytimer) {
clearTimeout(this.daytimer);
this.daytimer = null;
}
tomorrow.setDate(today.getDate() + 1);
tomorrow.setHours(0);
tomorrow.setMinutes(0);
tomorrow.setSeconds(1);
this.daytimer = setTimeout(this.daytimerAction, tomorrow.getTime() - today.getTime());
};
Calendar.prototype.updateCurrentDate = function() {
// Run code to update the day display
this.resetDaytimer();
};
Any thoughts? The only thing I can think of is that dashboard is pausing/cancelling the setTimeout when dashboard isn't running. Maybe there is a way to reset the timeout when dashboard is reactivated?
Figured it out. Apple documentation outlines the widget.onshow event that I can use to restart the timer as well as call updateCurrentDate() directly. There is also a widget.onhide event that can be used to pause the timer.

How to measure FPS & page paint time in Firefox and/or Chrome?

I am working on a performance test for HTML5 canvas & HTML5 SVG projects. As the projects are graphics-focused and require smooth operation, I've chosen refresh rate (fps) and page paint time (ms) as metrics. I am aware of the fact that values calculated from the javascript code are not representative enough, so these values should be taken from the browsers themselves. Therefore, javascript libraries like Mrdoob's stats.js cannot really be used (correct me if I'm wrong). Any info will be appreciated.
What I have found so far:
Mozilla Firefox:
FPS: windows.mozPaintCount
Page Paint Time: ?
Google Chrome:
FPS: built-in FPS-meter (seems to be working only for DOM-elements)
Page Paint Time: built-in PPT-meter (also for DOM-related stuff)
You can use requestAnimationFrame:
(function () {
var active = false;
var frames = 0;
var start;
var frame = function () {
frames = frames + 1;
if (active) {
window.requestAnimationFrame(frame);
}
};
window.FPS = {
start: function () {
active = true;
frames = 0;
start = window.performance.now();
frame();
},
end: function () {
active = false;
var seconds = (window.performance.now() - start) / 1000;
var fps = Math.round(frames / seconds);
alert(fps);
}
};
}());
You can perhaps use window.performance.now(). This new API was intended for things like this where you need sub-ms times.
It will (intend to) give you a high-resolution timestamp in higher resolution than ms but not without drawbacks:
Chrome currently returns milliseconds so no gain there (may be fixed in Canary by now)
Resolution depends on the underlying system
and mozPaintCount is a proprietary call which only works in Firefox.
So no matter how you twist and turn on this you will only get so far.
But you can try something like this:
function startPaintOperation() {
var startTime = 0, endTime = 0;
startTime = performance.now() || new Date().getTime(); // with fallback
... paint
endTime = performance.now() || new Date().getTime();
return endTime - startTime;
}
I don't think you can get much closer than this without using built-in tools of the browser.
See specifications here for more details.
Hope this helps.

Categories

Resources