How to wait for TextToSpeech initialization on Android

旧巷老猫 提交于 2019-12-01 18:55:11

You need to initialize the TTS system within e.g. the activities onCreate() method, so that you can use it later when the user e.g. clicks a button.

See e.g. https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L62 where setupspeak() is called and then later speak() ( https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L344 ) which is then called when the user clicks the 'speak' button.

public void init(final Context context, final OnProgressStart onStart) {
    _mTts = new TextToSpeech(context, new OnInitListener() {
        // Implements TextToSpeech.OnInitListener.
        public void onInit(int status) {
            // status can be either TextToSpeech.SUCCESS or TextToSpeech.ERROR.
            if (status == TextToSpeech.SUCCESS) {
                _isInitialized = true;
                Services.getTTSS().setLanguage();
                LogUtil.logInfo("TTS connected", this);
                if(onStart != null)
                    onStart.onStart();
            } else {
                // Initialization failed.
                Log.e(Constants.LOGTAG, this.getClass().getName()
                        + " Could not initialize TextToSpeech.");
            }
        }
    });

I also used the thread sleep, but it seems it doesn't work anymore and actually there is a better way handling this. Just pass a callback using simple interface like:

    init(context, new OnProgressStart() {               
            public void onStart(String... args) {
                startSpeak();                   
            }
        });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!