javascript – 使用cancel()方法的JS SpeechSynthesis问题

我想在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描述如下:

This method removes all utterances from the queue. If an utterance is
being spoken, speaking ceases immediately. This method does not change
the paused state of the global SpeechSynthesis instance.

谢谢答案:)

最佳答案 我刚遇到同样的问题,在取消后发言会导致没有说话.

我在clear()调用之后添加了一个小超时(250ms),它似乎工作:

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