Skip to content Skip to sidebar Skip to footer

Texttospeech Initialization On Android -- What If It Fails?

In Android, if a TextToSpeech instance fails to initialize (the callback invoked indicating the completion of the TextToSpeech engine initialization returns TextToSpeech.ERROR), do

Solution 1:

For your main question read the docs of the speak() method (here):

This method is asynchronous, i.e. the method just adds the request to the queue of TTS requests and then returns.

So unless your tts instance is null, it shouldn't throw any exception or crash the app, but just return the error code.

Also, the reason I can't just find out for myself is that I don't know how to simulate the error.

Try to use constructor (see docs) that expects as third parameter String engine and put invalid package name there. It should probably result in error then. (or disable/uninstall all TTS engines on your device/emulator)

Important thing to note regarding constructor is:

In a case of a failure the listener may be called immediately, before TextToSpeech instance is fully constructed.

So unless the status is SUCCESS, you shouldn't touch your ttsin the listener (of course you can use the tts afterwards as in your example) because it might not even be assigned / initialized yet.

Solution 2:

I had this problem, then I noticed that on some devices TTS may be deactivated. So I've just done the following

try {
        Intentintent=newIntent();
        intent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(intent, 0);
    } catch(ActivityNotFoundException exception) {
        Uriuri= Uri.parse("market://details?id=" + "com.google.android.tts&hl=fr");
        IntentgoToMarket=newIntent(Intent.ACTION_VIEW, uri);
        goToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {
            startActivity(goToMarket);
        } catch (ActivityNotFoundException e) {
            startActivity(newIntent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + "com.google.android.tts&hl=fr")));
        }
    } 

Solution 3:

You can try with this code.

Use language_codes from https://www.w3schools.com/tags/ref_language_codes.asp.

mLanguage = newLocale(language_codes);

tts = newTextToSpeech(mContext, newTextToSpeech.OnInitListener() {
        @OverridepublicvoidonInit(int status) {
            if (status != TextToSpeech.ERROR) {
                intresult= tts.setLanguage(mLanguage);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Log.e("Text2SpeechWidget", result + " is not supported");
                }
            }
        }
    });

Post a Comment for "Texttospeech Initialization On Android -- What If It Fails?"