Global TTS in Android

故事扮演 提交于 2019-12-01 22:38:04

Initialize your global instance from onActivityResult(), after you know that TTS data is available. Your app needs an activity, so do it from the entry activity, all subsequent ones will be able to use your global instance once it is initialized. Also think about when and how you will shut it down.

You don't need to use the ACTION_CHECK_TTS_DATA. Instead use isLanguageAvailable like this: (make sure to call this only after onInit is complete)

    // check if language is available
    switch (tts.isLanguageAvailable(locale))
    {
        case TextToSpeech.LANG_AVAILABLE:
        case TextToSpeech.LANG_COUNTRY_AVAILABLE:
        case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
            Log.d(TAG, "SUPPORTED");
            break;
        case TextToSpeech.LANG_MISSING_DATA:
            Log.d(TAG, "MISSING_DATA");//launch the install data activity
            break;
        case TextToSpeech.LANG_NOT_SUPPORTED:
            Log.d(TAG, "NOT SUPPORTED");//report failure
            break;
    }
qix

Here's some answers by gregm again to similar questions:

TTS - CHECK_VOICE_DATA_FAIL - Check engine availlable or

Why is the ACTION_CHECK_TTS_DATA Intent "awkward to use"?

that also recommend just using TextToSpeech.isLanguageAvailable() instead of ACTION_CHECK_TTS_DATA, along with a pointer to a helper class.

I've tested this on some android 4.1.2 phones with Locale.US, and it activates the TTS engine fine, and plays nicely with 3rd party engines. When testing on an old android 1.6 phone (G1), looks like the stock TTS engine is not installed (LANG_MISSING_DATA). The following code in that case will redirect to the store to install:

Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);

After which, using the tts engine within the app works fine. Basically, the old blog post from the android guys is a bit overkill and dated, as it does not play nicely with Android 4.x in my experience (ANDROID_CHECK_TTS_DATA always returned CHECK_VOICE_DATA_MISSING_DATA on me in Android 4.x).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!