Search code examples
text-to-speech

why SpeechSynthesisUtterance is not working on Chrome


I used the following code which shows Chrome supports SpeechSynthesisUtterance and the code works well on FireFox and Safari, but it is not working on Chrome (no sound). Why? Thank you.

<html>
    <head>
    </head>
    <body>
        <form>
            <input type='text'></input>
            <select></select>
        </form>
        <script>
            
            if ( 'speechSynthesis' in window ) {
                var to_speak = new SpeechSynthesisUtterance('Hello world!');
                window.speechSynthesis.speak(to_speak);
            } else {
                alert('not support ');
            }
        </script>
    </body>
</html>

https://codepen.io/sharkdeng/pen/xxOVeqb


Solution

  • It's because in Chrome speech synthasis requires user interaction before it speaks e.g. a button click.

    I've added to your code to put the speak function behind the button's click event.

    button.addEventListener('click', () => {
      if ( 'speechSynthesis' in window ) {
        const to_speak = new SpeechSynthesisUtterance(input.value || 'Hello world!');
        speechSynthesis.cancel();
        speechSynthesis.speak(to_speak);
      } else {
        alert('not supported');
      }
    });
    <form>
      <input type='text' id="input"></input>
      <select id='voiceSelect'></select>
      <button type="button" id="button">Speak</button>
    </form>