Reputation: 73
i have an issue changing dynamically the language of the text-to-speech, the first play is correct the second use the previous language. Here the code:
$('.audio-btn').click(function(){
let m = $(this).data('content');
let lang = $(this).data('lang');
var msg = new SpeechSynthesisUtterance();
var voices = window.speechSynthesis.getVoices();
msg.voice = voices[1];
msg.voiceURI = "native";
msg.volume = 1;
msg.text = m;
msg.lang = lang;
speechSynthesis.speak(msg);
})
and here the button i use:
<button class="audio-btn" data-content="Hola como estas?" data-lang="es-ES"></button>
<button class="audio-btn" data-content="Salut, comment ca va?" data-lang="fr-FR"></button>
thanks
Upvotes: 2
Views: 619
Reputation: 17594
I have rewritten your code a little. The problem with you was the binding. Try this:
in the console log you will see the index of using pronunciation.
const btns = document.querySelectorAll('button')
btns.forEach((el) => {
el.addEventListener('click', e => {
const msg = new SpeechSynthesisUtterance();
const txt = e.target.getAttribute('data-content');
const lang = e.target.getAttribute('data-lang');
const langCode = lang.split('-')[0]
let s = setSpeech();
s.then((voices) => {
//const voices = window.speechSynthesis.getVoices();
console.log(voices.findIndex(a => a.lang == langCode));
msg.voice = voices[voices.findIndex(a => a.lang == langCode)];
msg.text = txt;
msg.lang = lang;
msg.volume = 1;
msg.voiceURI = "native";
window.speechSynthesis.speak(msg);
});
})
})
function setSpeech() {
return new Promise(
function (resolve, reject) {
let synth = window.speechSynthesis;
let id;
id = setInterval(() => {
if (synth.getVoices().length !== 0) {
resolve(synth.getVoices());
clearInterval(id);
}
}, 10);
}
)
}
<button class="audio-btn" data-content="Hola como estas?" data-lang="es-ES">es</button>
<button class="audio-btn" data-content="Salut, comment ca va?" data-lang="fr-FR">fr</button>
<button class="audio-btn" data-content="Hello World! How are you?" data-lang="en-EN">en</button>
<button class="audio-btn" data-content="Alles klar? Jawohl! " data-lang="de-DE">de</button>
Upvotes: 1