Search code examples
javascriptgoogle-chrometext-to-speechspeech-synthesis

window.speechSynthesis.speak(msg) not working until button click


The brief page below does not work. Specifically, "window.speechSynthesis.speak(msg)" does not work until the button has been pressed. If the button has been pressed then the "Hello" message works. If it has not then any calls to "window.speechSynthesis.speak(msg)" do not produce any audible output.

Suspecting that it has something to do with initialization of speechSynthesis - some things have been tried below to ensure that it is initialized when "Hello" is called. None have worked. Although it seems like it should have. It seems like it is getting properly initialized only if it is called from the button press.

The setup of the SpeechSynthesisUtterance itself is the same whether called from the button or the timeout. That setup works when called by the button. But nowhere else until it has been called by the button.

What is wrong here?

<!DOCTYPE html>
<html>

    <head>
        <title>Voice Test 3</title>
    </head>

    <body>

        <div id="header">User Interface Terminal</div>
        <input type="text" id="control_box"></input><br>
        <button id="startButton" onclick="voicemessage('Button');">start</button><br>
        <script>

            function voicemessage(ttstext) {
                var msg = new SpeechSynthesisUtterance(ttstext);
                msg.volume = 1;
                msg.rate = 0.7;
                msg.pitch = 1.3;
                window.speechSynthesis.speak(msg);
                document.getElementById('control_box').value = ttstext; 
            }


            window.speechSynthesis.onvoiceschanged = function() {
                document.getElementById('control_box').value = "tts voices recognized";
                window.setTimeout(function() {
                    voicemessage("Hello");
                }, 5000);
            };

            window.addEventListener('load', function () {
                var voices = window.speechSynthesis.getVoices();
            })

        </script>

    </body>

</html>

Solution

  • This may be due to the browser itself... Recent updates in some browsers (Firefox and Chrome) have policies to prevent audio from being accessed unless some user interaction triggers it (like a button click)...