Search code examples
htmlspeech-synthesis

HTML5 speech synthesis not respecting locale in PC computers


My web app uses the Speech Synthesis API. My problem is simple: I setup the utterance and its locale. On (my) MAC computers, it works, ie. speaks with the requested locale. On Windows Computers (the ones I tried), it always uses English.

var mUtterance=new SpeechSynthesisUtterance(),
mUtterance.text="<text in spanish for example>";
mUtterance.lang="es";
window.speechSynthesis && window.speechSynthesis.speak(mUtterance);

why would this happen?

I'm using the latest chrome version (just updated) in both platforms.


Solution

  • I found why...

    If I specify the locale as the full code, es-ES, it works.

    Looks like Chrome/MAC versions are able to choose the default variant for a requested locale, while in Chrome/PC version you always have to specify the full locale code (language + variant). This makes my life harder, because for example Spanish has dozens of variants, and if somebody only has one of them installed, you have to explicitly select it, or otherwise the engine will default to English :(

    I wrote a small function to find any locale variant (the first found) for a given language:

    findLocaleCode=function(lang) {
        var voices=window.speechSynthesis.getVoices();
        for (var i=0, len=voices.length; i<len; i++) try {
            var voice=voices[i];
            if (voice.lang.indexOf(lang)==0) return voice.lang;
        } catch (e) {}
        return null;
    };
    

    so I can do:

    mUtterance.lang=findLocaleCode("es");
    

    and it will get es-ES, es-AR or whatever from the voice list.