Search code examples
javascripthtmlgoogle-chromespeech-synthesis

How to insert pause in speech synthesis with grammatical hints


I am writing a simple spelling test app using the HTML5 SpeechSynthesis API. The text I would like my app to say is something like the following: "The spelling word is Cat. The cat chased the dog.".

The API tends to race without much of a pause from the first sentence to the second. I wonder if there is a way to insert a bit of a pause between the 2 sentences. I realize I could create 2 separate utterances and use the pause() call. However the code would be simpler and less brittle if I could simply insert grammatical hints.

Normally in spoken English, one tends to pause a little longer between paragraphs. So I inserted a newline character in my text, but there was no noticeable impact.

I also tried using an ellipsis.

Is there any way to do this or am I stuck breaking everything into separate utterances?


Solution

  • Just insert

    <silence msec="5000" />
    

    in the text for 5 sec waiting (Source).

    Disclaimer: This code works only in an appropriate user agent.

    // code taken from https://richjenks.com/dev/speechsynthesis/
    var utterance  = new SpeechSynthesisUtterance(),
        speak      = document.getElementById("speak"),
        text       = document.getElementById("text");
    
    // Delay links and events because speechSynthesis is funny
    speechSynthesis.getVoices();
    setTimeout(function () {
        // Add event listeners
        var voiceLinks = document.querySelectorAll(".voice");
        for (var i = 0; i < voiceLinks.length; i++) {
            voiceLinks[i].addEventListener("click", function (event) {
                utterance.voice = speechSynthesis.getVoices()[this.dataset.voice];
            });
        }
    }, 100);
    
    // Say text when button is clicked
    speak.addEventListener("click", function (event) {
        utterance.text = text.value;
        speechSynthesis.speak(utterance);
    });
    <textarea id="text" rows="5" cols="50">Hi <silence msec="2000" /> Flash!</textarea>
    <br>
    <button id="speak">Speak</button>