I am writing a code where A video will play and then through faceapi we will catch the emotion of the user every second so far every thing we going good As soon as I added one validation that if face is not detectable for 5 seconds it will pause the video and stop the camera until user play it again after adding this validation my code is running 3 times in a second.
I am attaching screenshot and code also
- screenshot if video is normally running it will check after every single secondhere are the normal results
- Alert for userr which will come and pause the video
- Result after no detections you can see now its running multiple time in single second
below is the code
var nofacefound = 0;
let videotempid = videotags[1];
var titleofvideo = videotags[1].title;
videotempid.addEventListener('play', ()=> {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true}).then(function(stream) {
camarea.srcObject = stream;
camarea.play();
});
}
});
camarea.addEventListener('play', () => {
setInterval(async() => {
// eslint-disable-next-line no-undef
const detections = await faceapi.detectAllFaces(camarea, new faceapi.TinyFaceDetectorOptions()).withFaceExpressions();
if(detections.length == 1) {
//copying the array
const expression = detections[0].expressions;
//sorting the array
const predictedemotion = Object.fromEntries(Object.entries(expression).sort(([,a],[,b]) => b-a)
);
var emotionstate = Object.keys(predictedemotion)[0];
var secondemotion = Object.keys(predictedemotion)[1];
console.log(secondemotion);
var vidtimestamp = videotempid.currentTime;
var courseid = document.getElementById('courseid').innerHTML;
var tempdata = {"courseid":courseid,
"Video Title": titleofvideo,
"video time stamp": vidtimestamp,
"Emotion": emotionstate,
};
console.log(tempdata);
} else {
nofacefound = ++nofacefound;
if(nofacefound > 4)
{
videotempid.pause();
window.alert("we are unable to find your face please check your camera or adjust your position");
nofacefound = 0;
camarea.srcObject = null;
}
}
},1000);
});
videotempid.addEventListener('pause', ()=>{
camarea.srcObject = null;
});`
How I can run this code only one time per second or like If 5 seconds face is not detectable it will pause but as soon as use will play the video it will just run every single second. If I remove this 5 second detection validation then its working fine