get the text to speak duration of a message (javascript, SpeechSynthesisUtterance, chrome) - javascript

Is it possible to get the time that is needed to read a specific message ? I would like to use the SpeechSynthesisUtterance Web API and it only has to work in google chrome.
Would it be recommendet to use a third party libary ? Is it viable to messure the time in the background ?

For a workaround (using SpeechSynthesisUtterance) I meassure the time with the help of the onend event. This is not feasible for all situations, since it will take some time to meassure and is not very precise. You could increase the speed (up to 10) but it will get very unprecise.
var speed = 2;
var text = "Test";
var speech = new SpeechSynthesisUtterance(text);
var speakDuration;
speech.volume = 0;
speech.rate = speed;
speech.onend = function (event) {
speakDuration = event.elapsedTime / speed;
console.log(speakDuration)
};
window.speechSynthesis.speak(speech);

Related

Finding device uniqueness using Canvas Fingerprinting

Currently I am using Canvas Fingerprinting and other device parameters to find the unique device. But in recent post i came to hear that Canvas Fingerprinting is going to be blocked by Firefox browser. So i need alternate solution for identifying devices effectively. Can anyone suggest me a effective way to achieve this?
var _speedconstant = 8.9997e-9; //if speed=(c*a)/t, then constant=(s*t)/a and time=(a*c)/s
var d = new Date();
var amount = 150000000;
var estprocessor = 1.7; //average processor speed, in GHZ
console.log("JSBenchmark by Aaron Becker, running loop "+amount+" times. Estimated time (for "+estprocessor+"ghz processor) is "+(Math.round(((_speedconstant*amount)/estprocessor)*100)/100)+"s");
for (var i = amount; i>0; i--) {}
var newd = new Date();
var accnewd = Number(String(newd.getSeconds())+"."+String(newd.getMilliseconds()));
var accd = Number(String(d.getSeconds())+"."+String(d.getMilliseconds()));
var di = accnewd-accd;
//console.log(accnewd,accd,di);
if (d.getMinutes() != newd.getMinutes()) {
di = (60*(newd.getMinutes()-d.getMinutes()))+di}
spd = ((_speedconstant*amount)/di);
console.log("Time: "+Math.round(di*1000)/1000+"s, estimated speed: "+Math.round(spd*1000)/1000+"GHZ");
This utility was free. It's probably better for validating performance than for fingerprinting.

firefox crash with angular ( Garbage Collector troll? )

----EDIT the question was to long and to hard to understand------
Here is a working exemple : http://codepen.io/anon/pen/Mwapgb
WARNING : This will make firefox CRASH ! , if you dare, click around 500 time on any div (i suggest to use a tool to simulate it. Rip mouse)
But This http://codepen.io/anon/pen/eNNqde
Wont make firefox crash
What is the difference :
function GetDateFromDatetimePython(stringdate){ // IT CRASH
var partieDate = stringdate.split(' ');
var ymd = partieDate[0].split('-');
var hms = partieDate[1].split(':');
return new Date(Date.UTC(ymd[0],ymd[1]-1,ymd[2],hms[0],hms[1],hms[2],0));
}
function GetDateFromDatetimePython(stringdate){ // IT DON'T
var partieDate = stringdate.split(' ');
var tmp = partieDate[0]; // add this
var tmp2 = partieDate[1]; // add this
var ymd = tmp.split('-'); // change this
var hms = tmp2.split(':'); // change this
return new Date(Date.UTC(ymd[0],ymd[1]-1,ymd[2],hms[0],hms[1],hms[2],0));
}
I'm going crazy. What is wrong with the first practice ?
Ok , it's stupid to make 3 split, i could combined in 1 . Whenever. WHY does this blow up firefox , Why aren't Chrome nor IE affect ?
May be you are trapped into some infinite loop or a process is instantiated which involves heavy processing which drains all the memory available with your browser.

How to calculate time interval between two "keyup" events

i need to create some kind of elementary pos with javascript. I have an barcode scanner that work like a keyboard. So i want to automaticaly detect when the input come from the barcode and then create a report with that codes. I think an good idea is to calculate the difference of typing speed because the scanner is really fast:
if there a dalay between keyup > 300ms = another scan
var speed = new Date().getTime() - lastkey;
lastkey = (new Date()).getTime();
console.log(speed);
if(speed > 300) {
//little delay for prevent computer overhead o_O
var create_d = setTimeout(createchange,300)
} else {
//barcode sanning continue
clearTimeout(create_d)
}
JsFiddle link <
Using pure JS:
document.body.onkeydown = function ()
{
var time = this._time;
var timestamp = new Date().getTime();
if (time)
console.log(timestamp - time);
this._time = timestamp;
}
The console will display difference between keydown events (in ms)

How can one force the browser to redraw an image?

I'm working on a JavaScript game that involves throwing a snowball. I need the snowball to render as often as possible during its flight path. Chrome does all the calculations, including setting the style.left and style.top properties, but doesn't actually redraw the snowball until it reaches its destination. Opera doesn't have this problem.
A relevant point is that putting in an alert() after renderSnowball() fixes the problem, except using the alert() is an obvious issue.
Here's my code so far:
function throwSnowball()
{
var theta = parseFloat(angleField.value) * Math.PI/180 ;
var Vir = parseFloat(velocityField.value) ;
if (!isNaN(Vir) && !isNaN(theta) )
{
Vix = Math.cos(theta) * Vir * 50;
Viy = Math.sin(theta) * Vir * 50;
time = new Date() ;
var timeThrown = time.getTime() ;
while (snowballPosY > 0)
{
current = new Date() ;
var currentTime = current.getTime() ;
var timeElapsed = (currentTime - timeThrown)/5000 ;
snowballPosX += Vix * timeElapsed;
snowballPosY += Viy * timeElapsed;
Viy -= GRAVITY * timeElapsed ;
renderSnowball() ; //renderSnowball() sets the style.left
// and style.top properties to snowballPosX pixels
// and snowballPosY pixels respectively
timeThrown = currentTime ;
}
snowballPosX = 0 ;
snowballPosY = 50 ;
renderSnowball() ;
}
}
You're totally blocking the main thread. Have you tried using a setTimeout (even with a zero timeout) to allow other things to happen during your animation?
If you're willing to use experimental technology, requestAnimationFrame would be even better.
Edit: the setTimeout approach would look something like this (replacing the while loop):
var drawAndWait = function() {
if (snowballPosY > 0) {
// movement/drawing code here
setTimeout(drawAndWait, 20 /* milliseconds */);
} else {
// reset code that would normally go after your while loop
}
};
drawAndWait();
So each time the drawing finishes, it arranges for itself to be invoked again, if appropriate. Note that your throwSnowball function will return quickly; the throwing isn't actually done until later on. This takes awhile to get used to doing correctly; don't be too concerned if it's not intuitive at first.
Try getting out of the tight loop. Chrome may not want to redraw until your function exits. Try using setInterval or setTimeout to give Chrome a chance to repaint.

HTML5 Video - Percentage Loaded?

Does anyone know what event or property I need to query in order to get a percentage figure of the amount an HTML5 video has loaded? I want to draw a CSS styled "loaded" bar that's width represents this figure. Just like You Tube or any other video player.
So just like you tube a video will play even if the whole video hasn't loaded and give the user feedback on how much of the video has loaded and is left to load.
Just like the Red Bar on YouTube:
The progress event is fired when some data has been downloaded, up to three times per second. The browser provides a list of ranges of available media through the buffered property; a thorough guide to this is available on Media buffering, seeking, and time ranges on MDN.
Single load start
If the user doesn't skip through the video, the file will be loaded in one TimeRange and the buffered property will have one range:
------------------------------------------------------
|=============| |
------------------------------------------------------
0 5 21
| \_ this.buffered.end(0)
|
\_ this.buffered.start(0)
To know how big that range is, read it this way:
video.addEventListener('progress', function() {
var loadedPercentage = this.buffered.end(0) / this.duration;
...
// suggestion: don't use this, use what's below
});
Multiple load starts
If the user changes the playhead position while it's loading, a new request may be triggered. This causes the buffered property to be fragmented:
------------------------------------------------------
|===========| |===========| |
------------------------------------------------------
1 5 15 19 21
| | | \_ this.buffered.end(1)
| | \_ this.buffered.start(1)
| \_ this.buffered.end(0)
\_ this.buffered.start(0)
Notice how the number of the buffer changes.
Since it's no longer a contiguous loaded, the "percentage loaded" doesn't make a lot of sense anymore. You want to know what the current TimeRange is and how much of that is loaded. In this example you get where the load bar should start (since it's not 0) and where it should end.
video.addEventListener('progress', function() {
var range = 0;
var bf = this.buffered;
var time = this.currentTime;
while(!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
var loadStartPercentage = bf.start(range) / this.duration;
var loadEndPercentage = bf.end(range) / this.duration;
var loadPercentage = loadEndPercentage - loadStartPercentage;
...
});
The other awnsers didn't work for me so I started digging into this problem and this is what I came up with. The solutions uses jquery to make an progressbar.
function loaded()
{
var v = document.getElementById('videoID');
var r = v.buffered;
var total = v.duration;
var start = r.start(0);
var end = r.end(0);
$("#progressB").progressbar({value: (end/total)*100});
}
$('#videoID').bind('progress', function()
{
loaded();
}
);
I hope this helps others as well
Percentage fix for loaded string.. Output something like 99% loaded inside #loaded element...
function loaded() {
var v = document.getElementById('videoID');
var r = v.buffered;
var total = v.duration;
var start = r.start(0);
var end = r.end(0);
var newValue = (end/total)*100;
var loader = newValue.toString().split(".");
$('#loaded').html(loader[0]+' loaded...');
$("#progress").progressbar({
value: newValue
});
}
I think best event to update the buffered progress bar is timeupdate. whenever time of the media is updated event is fired.
It gives buffered property which we can use like this
audio.addEventListener('timeupdate', function () {
if (this.duration) {
let range = 0;
let bf = this.buffered;
let time = this.currentTime;
while (!(bf.start(range) <= time && time <= bf.end(range))) {
range += 1;
}
let loadStartPercentage = bf.start(range) / this.duration;
let loadEndPercentage = bf.end(range) / this.duration;
let loadPercentage = (loadEndPercentage - loadStartPercentage) * 100;
//Update your progressbar DOM here
}
});
Best advantage of this event is this is fired when media is played. Whereas progress event is fired when media is downloaded and notified by browser.
So just like youtube, buffered percentage can only be shown when media is played
My answer is better than all of the other ones because you want to update buffer progress when the video is paused. This happens with the progress event. The time update event fires when progress fails, as it sometimes does.
$("#video").on("timeupdate progress", function(){
var video = document.getElementById("video");
var vidDur = video.duration;
for(var i = 0; i <= vidDur; i++){
var totBuffX = video.buffered.end(i);
var perBuff = totBuffX/vidDur*100;
$("#xVidBuffX").css("width", perBuff+"%");
}
});
you only need video.buffered.end(i).

Categories