JS语音合成:cancel()方法存在问题

6
我想在谷歌浏览器中使用window.SpeechSynthesis的cancel方法,以切断一个utterance并开始一个新的(这样你就不必听到所有还在队列中的utterances)。请保留HTML标记格式。
var test = new SpeechSynthesisUtterance("Test");
window.speechSynthesis.speak(test);  
window.speechSynthesis.cancel();
var test2 = new SpeechSynthesisUtterance("Test2");
window.speechSynthesis.speak(test2);

期望的效果:以变量test开始语音,但由于cancel()立即取消了它。然后使用变量test2重新开始语音,应该可以正常工作。
当然,这并没有发生。但是所发生的是什么都没有发生。:D 看起来在cancel()之后调用speak()不会有任何作用。
API描述如下:
此方法从队列中删除所有话语。如果正在说话,则立即停止讲话。此方法不更改全局SpeechSynthesis实例的暂停状态。
感谢答案 :)
4个回答

2

我刚遇到了同样的问题,在取消后发出speak不会有任何话语被发出。

clear()调用后添加一个小超时(250毫秒),似乎可以解决这个问题:

var sayTimeout = null;

function say(text) {
    if (speechSynthesis.speaking) {
        // SpeechSyn is currently speaking, cancel the current utterance(s)
        speechSynthesis.cancel();

        // Make sure we don't create more than one timeout...
        if (sayTimeout !== null)
            clearTimeout(sayTimeout);

        sayTimeout = setTimeout(function () { say(text); }, 250);
    }
    else {
        // Good to go
        var message = new SpeechSynthesisUtterance(text);
        message.lang = "en-US";
        speechSynthesis.speak(message);
    }
}

1

使用您提供的代码,现在似乎可以工作了。

$(document).on("click", "#speak", function() {

  var test = new SpeechSynthesisUtterance("Test");
  window.speechSynthesis.speak(test);
  window.speechSynthesis.cancel();
  var test2 = new SpeechSynthesisUtterance("Test2");
  window.speechSynthesis.speak(test2);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="speak">CLICK ME TO HEAR TEXT</div>


确认。我在Chrome 76 / Windows 7中听到了“Test2”。 - Bob Stein

0
function texto_a_voz(reproducir, idioma) {

   var synth = window.speechSynthesis;
   var voices = [];
   voices = synth.getVoices();

   var utterThis = new SpeechSynthesisUtterance(reproducir);
   utterThis.voice = voices[idioma];
   utterThis.pitch = pitch.value;
   utterThis.rate = rate.value;

   if (synth.speaking) {
       // SpeechSyn is currently speaking, cancel the current utterance(s)
       synth.cancel();
       setTimeout(function () { synth.speak(utterThis); }, 250);
   }
   else {
       // Good to go
       synth.speak(utterThis);
   }
} 

-1

直接从p5speech库的示例中取出此代码。也许这可以作为一个解决方法?

    function parseResult()
    {
        // recognition system will often append words into phrases.
        // so hack here is to only use the last word:
        var mostrecentword = myRec.resultString.split(' ').pop();
        if(mostrecentword.indexOf("left")!==-1) { dx=-1;dy=0; }
        else if(mostrecentword.indexOf("right")!==-1) { dx=1;dy=0; }
        else if(mostrecentword.indexOf("up")!==-1) { dx=0;dy=-1; }
        else if(mostrecentword.indexOf("down")!==-1) { dx=0;dy=1; }
        else if(mostrecentword.indexOf("clear")!==-1) { background(255); }
        console.log(mostrecentword);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接