Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS SpeechSynthesis Problems with the cancel() Method

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 :)

like image 434
Erik Avatar asked Sep 08 '16 12:09

Erik


2 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);
    }
}
like image 158
Basuro Avatar answered Sep 24 '22 02:09

Basuro


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>
like image 29
user1063287 Avatar answered Sep 21 '22 02:09

user1063287