Reputation: 113
I'm writing a javascript code which I want to welcome users when they click the "start button". It's working, in english, but the point is that I want it to say things in Brazilian Portuguese (pt-BR). I tried a lot of solutions, but seems it will not work. Can anyone please help me?
The code is:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<script>
startTalking = function(line){
var text = new SpeechSynthesisUtterance();
text.lang = "pt-BR";
text.text = line;
speechSynthesis.speak(text);
}
</script>
</head>
<body>
<button id="startButton" onclick = "startTalking("Bem vindo!")"></button>
</body>
</html>
When I click the button the script works, but the text received in the parameter is spoken by a voice in English (USA).
Does anyone has any clue on how to fix it?
Thanks!!
Upvotes: 3
Views: 2453
Reputation: 113
Thanks for your reply Bruno. I got this situation solved the day next I posted the question but could not post the solution here. I solved this situation using this:
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<script>
var text;
var voices;
window.speechSynthesis.onvoiceschanged = function() {
text = new SpeechSynthesisUtterance();
voices = window.speechSynthesis.getVoices();
text.voiceURI = 'Google português do Brasil'; //discovered after dumping getVoices()
text.lang = "pt-BR";
text.localService = true;
text.voice = voices[15]; //index to the voiceURI. This index number is not static.
}
startSpeaking = function(line){
text.text = line;
speechSynthesis.speak(text);
}
</script>
</head>
<body>
<button id="startButton" onclick = "startTalking("Bem vindo!")"></button>
</body>
</html>
Once onvoiceschanged is asynchronous, this made everything work fine now!
Even I've already got it solved, I'm very grateful for your reply. Thanks a lot.
Best Regards,
Ulisses
Upvotes: 3
Reputation: 41
Watch this:
web speech api - speech synthesis .lang property not working
and this:
https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis/onvoiceschanged
For some reason, now you need to populate the voices list and only then you can choose the language/version you want.
Upvotes: 0