i want to use the cancel Method of window.SpeechSynthesis in Chrome, to cut off an Utterance and start a new one (so you dont have to hear all utterances which are still in queue)
var test = new SpeechSynthesisUtterance("Test");
window.speechSynthesis.speak(test);
window.speechSynthesis.cancel();
var test2 = new SpeechSynthesisUtterance("Test2");
window.speechSynthesis.speak(test2);
Expected: Start speech with var test , but cancel it instantly due to cancel(). Then start speech again with var test2 , which should work fine.
Well of course that did not happen. But what happened was nothing. :D It seemed like calling speak() after cancel() somehow does nothing.
The API Description is the following:
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.
Thx for answers :)
I just faced the same problem, issuing a speak after a cancel will result in no utterance being spoken.
I added a small timeout (250ms) after the clear() call and it seems to work:
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);
}
}
It seems to work now, using the code you provided.
$(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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With