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

speechSynthesis API not working


I'm trying to experiment with speechSynthesis API with the help of Eric's blog.

This fiddle is working fine, meaning there is no issue with the audio device permission for website (correct me if I'm wrong). I made my own fiddle but doesn't seems to be working (I mean it is not saying Hello world).

Here is my code:

function speak() {
    var msg = new SpeechSynthesisUtterance('Hello world');
    msg.rate = 0.7;
    msg.pitch = 1;
    window.speechSynthesis.speak(msg);
}
<button title="Click to listen" onclick="speak()">
         Say hello world
</button>

Update: The code is working here as pointed out by enhzflep but not in JSFiddle's editor

Any suggestions, kind folks?


Solution

  • Hmmm.Well, the snippet you've posted here on this page works for me, yet the fiddle containing the same code doesn't. However, if you change the 2nd drop-down to "No wrap - in <head>" then it's just fine.

    This is because jsfiddle wrapped your code into a function that was called when the document loaded, like this:

    <script type="text/javascript">//<![CDATA[ 
    window.onload=function(){
    function speak() {
        var msg = new SpeechSynthesisUtterance('Hello world');
        msg.rate = 0.7;
        msg.pitch = 1;
        window.speechSynthesis.speak(msg);
    }
    }//]]>  
    </script>
    

    By doing this, code outside of the window.onload handler, including the inline JS in your html can't 'see' your speak function.

    By changing the drop-down, jsFiddle generates different JS for the iframe that shows your result, like this:

    <script type="text/javascript">//<![CDATA[ 
    
    function speak() {
        var msg = new SpeechSynthesisUtterance('Hello world');
        msg.rate = 0.7;
        msg.pitch = 1;
        window.speechSynthesis.speak(msg);
    }
    //]]>  
    
    </script>