Tengo un problema al cambiar dinámicamente el idioma de texto a voz, la primera reproducción es correcta, la segunda usa el idioma anterior. Aquí el código:
$('.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); })y aquí el botón que uso:
<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>Gracias
He reescrito un poco tu código. El problema contigo era la encuadernación. Prueba esto:
en el registro de la consola verá el índice de uso de la pronunciación.
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>