我想在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实例的暂停状态。
获答答案:)
答案 0 :(得分:1)
我刚遇到同样的问题,在取消后发出发言会导致没有发言。
我在 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 :(得分: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);
}
}
答案 2 :(得分:0)
直接从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);
}
答案 3 :(得分:0)
使用您提供的代码,现在看来可以正常工作。
$(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>