Warm tip: This article is reproduced from serverfault.com, please click

SpeechSynthesis API onend callback not working

发布于 2014-05-06 00:17:28

I'm using the Speech Synthesis API on Google Chrome v34.0.1847.131. The API is implemented in Chrome starting in v33.

The text-to-speech works for the most part, except when assigning a callback to onend. For instance, the following code:

var message = window.SpeechSynthesisUtterance("Hello world!");
message.onend = function(event) {
    console.log('Finished in ' + event.elapsedTime + ' seconds.');
};
window.speechSynthesis.speak(message);

will sometimes call onend and sometimes not call it. The timing appears to be completely off. When it does get called, the printed elapsedTime is always some epoch time like 1399237888.

Questioner
huu
Viewed
0
4,211 2016-07-10 23:38:54

While this is how I found it to make it work, I am not sure if this is the right behavior....

First don't call the speak function it right away, use callback.

2nd, to get time use timeStamp instead of elapsedTime. You could have just used performance.now() as well.

var btn = document.getElementById('btn');
speechSynthesis.cancel()
var u = new SpeechSynthesisUtterance();
u.text = "This text was changed from the original demo.";

var t;
u.onstart = function (event) {
    t = event.timeStamp;
    console.log(t);
};

u.onend = function (event) {
    t = event.timeStamp - t;
    console.log(event.timeStamp);
    console.log((t / 1000) + " seconds");
};

btn.onclick = function () {speechSynthesis.speak(u);};

Demo: http://jsfiddle.net/QYw6b/2/

you get time passed and both events fired for sure.