Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextToSpeech setLanguage not working?

I am setting my TextToSpeech to use a particular language (English - UK), using the locale "en_GB". But it always uses my devices default language. Is there no way to set it programmatically? I have downloaded the files required for the language and when I change my TTS's default language to 'English - UK' it works but when the default is different the programmatic approach does not work. I have scoured the web to my best but am unable to resolve this issue.

    String ttsEngine = "com.google.android.tts";
    txt2Speech = new TextToSpeech(this, this, ttsEngine);
    //Locale ttsLocale = new Locale("eng", "GBR");
    txt2Speech.setLanguage(new Locale("en_GB"));

Tried several methods, but none are working. Can I not set my TTS's language programmatically?

Thank You

EDIT: In response to 'A Honey Bustard'

Other Code:

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener

My onInit()

public void onInit(int status) {
    // TODO Auto-generated method stub

}

Also I'm calling .setLanguage() in my onCreate(), as soon as my TextToSpeech is initialized. Is that correct? Also I'm only calling it once. It is not required to call it every time right? Also I'm testing on a GS7

like image 329
KISHORE_ZE Avatar asked Jul 04 '16 16:07

KISHORE_ZE


2 Answers

You need to set the language once the Text to Speech Engine has initialised correctly.

public void onInit(int status) {

    switch (status) {

        case SUCCESS:
        // Set the language here
        break;
        case ERROR:
         // Something went wrong. You can't set the language
        break;
    }
}

That should do it.

like image 101
brandall Avatar answered Nov 01 '22 00:11

brandall


Try the second Constructor from Locale that takes two Strings like this :

    txt2Speech.setLanguage(new Locale("en", "GB"));

EDIT :

Yes it is usually ok to do instantiate it in onCreate, and it usually only needs and should be done once.

All I can do is show you my working code, I am setting the default language after instantiating in onCreate() :

    textToSpeech = new TextToSpeech(getApplicationContext(), this);

    textToSpeech.setLanguage(Locale.getDefault());

In my app there are buttons in which you can change the language, which trigger this code (case British English) :

  textToSpeech.setLanguage(new Locale("en", "GB"));

Maybe it is not available somehow , there are some checks you can validate if the language and country is available. You might find your error there.

 if (textToSpeech.isLanguageAvailable(new Locale("en", "GB")) == TextToSpeech.LANG_COUNTRY_AVAILABLE
   && textToSpeech.isLanguageAvailable(new Locale("en", "GB")) == TextToSpeech.LANG_AVAILABLE) 

should return true.

like image 3
A Honey Bustard Avatar answered Nov 01 '22 00:11

A Honey Bustard