6

I have an script correctly running on chrome for windows, but when I try it on my android chrome, it doesn't works. It seems to be a problem of the voices, since the :

if ('speechSynthesis' in window)

returns true. I've tried some online examples (for example http://codepen.io/matt-west/pen/wGzuJ) and the "voices" selection list is empty.

Do I need to install something to make this work?

This code works in chrome for windows but not in chrome for android:

function playSentence(text) {    
     var msg = new SpeechSynthesisUtterance();    
     msg.text = text;
     window.speechSynthesis.speak(msg);
 }

 $(function () {
     playSentence("Hello world");
 });

Versions: Android 5.0.0 - Chrome 46.0.2490.76

user3192301
  • 61
  • 2
  • 4

1 Answers1

3

There are two issues

1) on mobile you need a user gesture to start play the text. Add it into an onclick handler see the following demo:

<body>
  <button id="btnPlay">Play</button>
  <script>
    function playSentence(text) {    
      var msg = new SpeechSynthesisUtterance();    
      msg.text = text;
      window.speechSynthesis.speak(msg);
    }

    $("#btnPlay").click(function() {
      playSentence("Hello world");
    });
</script>  

</body>

2) The demo is also broken :\ But there are two key parts which you need to take care of.

i. getVoices is asynchronus (mentioned in the Spec Errata) and you need to listen to the voiceschanged event, the reasoning is a little frustrating but makes sense, the Voice system is lazily loaded and the first call to getVoices would block the main thread so the first call on android returns 0 results and then fires an onvoiceschanged when the voices become available.

ii. The linked demo incorrectly sets the voice attribute on the utterance. This doesn't exist, instead you need to change the lang and optionally the voiceURI to change the default used voice as can be seen below and in the new demo.

if (voiceSelect.value) {
  var selectedVoice = speechSynthesis.getVoices().filter(function(voice) { return voice.voiceURI == voiceSelect.value; })[0];

  msg.voiceURI = selectedVoice.voiceURI;
  msg.lang = selectedVoice.lang;

}
Kinlan
  • 16,315
  • 5
  • 56
  • 88
  • Thanks for taking the time to reply. The problem is that there are no voices installed in that device (I dont know why, and I dont know if its a common problem). I installed a TTS program in android, and after that the problem got solved. Anyways, as you said apparently the "voice" attribute of the utterance as no effect, and I had to change the "lang" property. I think that solved the issue. I will test it further and I'll edit my original question. Thanks! – user3192301 Nov 27 '15 at 23:27
  • New demo is gone now :( – Syed M. Sannan Jul 03 '22 at 10:14