admin管理员组

文章数量:1391960

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>

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?

Share Improve this question edited Nov 30, 2017 at 6:05 Mr.X asked Jun 28, 2015 at 11:15 Mr.XMr.X 31.4k27 gold badges147 silver badges229 bronze badges 3
  • 1 i still cannot hear anything – rash Commented May 8, 2020 at 10:35
  • 1 @rash But I can :) I have tried it and seems working on Chrome – Mr.X Commented May 8, 2020 at 15:17
  • 1 in my case restarting browser helped – Asad Commented Jul 25, 2020 at 20:26
Add a ment  | 

1 Answer 1

Reset to default 3

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>

本文标签: javascriptspeechSynthesis API not workingStack Overflow