Text to speech through JS not working

I am trying to get my webpage to read out a piece of text
The problem is that I am not able to even import the library that I want to use.
The library is supposed to be built into the browser.

Code Sample:

from ._anvil_designer import Form1Template
from anvil import *
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
from anvil.js.window import SpeechSynthesis
class Form1(Form1Template):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run when the form opens.
    synth = SpeechSynthesis()
    voices_list = synth.getVoices()
    print(voices_list)

Clone link:
test speech synthesis | Anvil

Hi @aashraychegu, and welcome to the forum,

There’s definitely some context missing here.
Where did you find your code snippet? (for example)
The clone link provided isn’t quite the full clone link url - which means we can’t open it.

The MDN docs on SpeechSynthesis don’t show examples where SpeechSyntheses is a constructor.
Looking at the examples online it should look more like:

from anvil.js.window import speechSynthesis as synth

class Form1(Form1Template):
  def __init__(self, **properties):
    ...
    voices_list = synth.getVoices()
    print(voices_list)

Thank you so much for your help!
I found your fix really helpful, and it helped me get going on my project.

There seems to be another problem however, as to speak out a phrase, the speech synthesizer needs an utterance object, but I cannot find any way to use the utterance object.

SpeechSynthesisUtterance - Web APIs | MDN (mozilla.org)

Thank you,
Aashray

I believe that I have found a solution by using anvil.js.window.SpeechSynthesisUtterance() instead of trying to create an object.

My final code looks like this

from ._anvil_designer import main_pageTemplate
import anvil
from anvil import *
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
from anvil.js.window import speechSynthesis as synth
class main_page(main_pageTemplate):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)
    
    # Any code you write here will run when the form opens.
    voices_list = synth.getVoices()
    print(voices_list)
    synth.speak(anvil.js.window.SpeechSynthesisUtterance("hello"))

Hopefully this is helpful for people.

1 Like

Thanks for posting your solution! I now get text to speech. However,

voices_list = synth.getVoices()
print(voices_list)

yields an empty list. Any idea why getVoices() is not retrieving voices??

This might be because of your browser’s permissions, what browser you have, or what tts voices are installed on your browser/computer.
I know that Microsoft Edge, Google Chrome, and Safari work.