Chrome 使用cancel()方法的JS语音合成问题

bbuxkriu  于 11个月前  发布在  Go
关注(0)|答案(4)|浏览(123)

我想在Chrome中使用window.SpeechSynthesis的cancel方法,以切断一个话语并开始一个新的话语(因此您不必听到仍在队列中的所有话语)

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

字符串
预期:使用var test启动语音,但由于cancel()而立即取消。然后使用var test2再次启动语音,这应该可以正常工作。
好吧,当然这没有发生。但是发生的事情什么也不是。:D看起来好像在cancel()之后调用speak()没有什么作用。
API说明如下:
此方法从队列中删除所有发音。如果正在说出发音,则立即停止说话。此方法不会更改全局SpeechSynthesis示例的暂停状态。
Thx for answers:)

eni9jsuy

eni9jsuy1#

我刚刚遇到了同样的问题,在一个取消后发出一个发言将导致没有发言。
我在**clear()**调用后添加了一个小的超时(250 ms),它似乎可以工作:

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);
    }
}

字符串

aoyhnmkz

aoyhnmkz2#

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

$(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>
u91tlkcl

u91tlkcl3#

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);
   }
}

字符串

yuvru6vn

yuvru6vn4#

这段代码直接取自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);
    }

字符串

相关问题