How to wait for TextToSpeech initialization on Android

后端 未结 2 1083
天涯浪人
天涯浪人 2021-01-19 06:47

I am writing an activity that speaks to the user and I\'d really like to block on TextToSpeech initialization - or else time out. How can I get my thread to wait?

I

相关标签:
2条回答
  • 2021-01-19 07:14
    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();                   
                }
            });
    
    0 讨论(0)
  • 2021-01-19 07:16

    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.

    0 讨论(0)
提交回复
热议问题