SpeechSynthesis API一次回调无法正常工作

huu*_*huu 28 javascript google-chrome text-to-speech speech-synthesis google-text-to-speech

我在Google Chrome v34.0.1847.131上使用语音合成API.从v33开始,该API在Chrome中实施.

除了分配回调时,文本到语音大部分都有效onend.例如,以下代码:

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

有时会打电话onend,有时不打电话.时机似乎完全没有了.当它被调用时,打印elapsedTime总是像一些时代一样1399237888.

tec*_*ace 20

根据Kevin Hakanson 的回答中提到的bug的评论,这可能是垃圾收集的问题.在调用之前将话语存储在变量中似乎可以解决问题:speak

window.utterances = [];
var utterance = new SpeechSynthesisUtterance( 'hello' );
utterances.push( utterance );
speechSynthesis.speak( utterance );
Run Code Online (Sandbox Code Playgroud)

  • 谢谢你!一旦我改变了范围我的话语变量我就不再有问题了.我同意可能存在与浏览器内部GC相关的错误. (2认同)

Muh*_*mer 9

虽然这是我发现它使它工作的方式,但我不确定这是否是正确的行为....

首先不要立即调用speak函数,使用回调.

2,获取时间timeStamp而不是elapsedTime.你也可以使用performance.now()它.

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);};
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/QYw6b/2/

你得到时间,两个事件肯定会被解雇.


小智 5

您可以像我为 Speakerbot ( http://www.speakerbot.de/ )所做的那样使用 EventListener 开始和结束。

在这里,说话时我的脸色会发生变化。

newUtt = new SpeechSynthesisUtterance();

newUtt.addEventListener('start', function () {
     console.log('started');
})

newUtt.addEventListener('end', function () {
     console.log('stopped');
})
Run Code Online (Sandbox Code Playgroud)