I used speechSynthesis API in this way:
speechSynthesis.speak(new SpeechSynthesisUtterance(\"hello world\"));
But right now I get error aft
Although I haven't found any way to ask permission, the user can enable permission in Google Chrome:
Click on the icon on the left of the URL bar, and open Site settings
Change the Sound setting from "Automatic (default)" to "Allow"
After doing that, the site will be able to make sounds without any user interaction, including speech.
Unfortunately, I haven't found a way in code to know whether this is working or not. (Perhaps we could try one of the other audio APIs and see if it responds with an error message.)
If you set your site address as "trusted" in chrome://settings/content/sound it seems to enable sound and speech synthesis even without user interactions.
I use Chrome in a TV just as a system monitor, using kiosk mode and without any user interactions. It doesn't even have keyboard and mouse. Still, I was able to enable in some versions of Chrome/Chromium, but not in others.
I resorted to swal("Click OK to speak").then(() => speakButton.click());
(with https://sweetalert.js.org) -- https://patarapolw.github.io/tts-api/?q=你好&lang=zh-CN&rate=0.8
Note that if (confirm("Click OK to speak")) speakButton.click()
doesn't work.
This is part of Chrome's new policies regarding making sound from web-pages.
You simply need your user to provide an user-gesture (for which you can find a list here) during the lifetime of the parent document (i.e the event may long be dead, as long as the user ever interacted with the page).
Note that these events can even traverse frames, so for instance, in StackOverflow, the simple fact that you do have to click on the "Run" button will make the inner frame allowed to execute this code:
const ut = new SpeechSynthesisUtterance('No warning should arise');
speechSynthesis.speak(ut);
And in your code, you simply have to provide some kind of an UI that will ensure your users have interacted with the page before you call this method (e.g a button / toggle will do perfectly).
This error means entire document (Website) has no user interaction and Google Chrome update its policy regarding making sound from the website without user interaction.
User interaction means: click, dblclick, mouseup, pointerup, reset, submit etc.
Solution:
So, if you want to run speechSynthesis.speak();
without real user interaction, then you just create temporary user interaction using a method like .click()
, etc.
A simple hack, without needing a real user activity, is to execute a click event on a hidden button like so.
document.querySelector('button').click();
var msg = new SpeechSynthesisUtterance('Test');