How to wait for TextToSpeech to initialize on Android

I am writing an action that speaks to the user, and I really would like to block TextToSpeech initialization - or timeout. How can I make my thread wait?

I tried:

 while (! mIsTtsReady || i>limit) try { Thread.sleep(100); i++; ... };

together with:

 @Override
 public void OnInit() { mIsTtsReady = true; }   // TextToSpeech.OnInitListener

But OnInit () never starts. It seems that OnInit is executing in my thread (through a message to my Looper actions?), Which is in a closed sleep () loop.

It seems wrong to put the bulk of my code ("after init") in OnInit. Moving it to Runnable, then run () and sleep as above in this runnable. But now my code is in a new thread and needs to be explicitly synchronized with the user interface, etc., And it all becomes very messy.

What is the right way - or at least the one that works :) - for this?

Thank!

+3
source share
2 answers

You need to initialize the TTS system, for example, the onCreate () method, so that you can use it later when the user, for example. presses a button.

See https://github.com/pilhuhn/ZwitscherA/blob/master/src/de/bsd/zwitscher/OneTweetActivity.java#L62 for setupspeak () and then () ( https: // github. com / pilhuhn / ZwitscherA / blob / master / src / de / bsd / zwitscher / OneTweetActivity.java # L344 ), which is then called up when the user clicks the talk button.

+1
source
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.");
            }
        }
    });

sleep, , , . , :

    init(context, new OnProgressStart() {               
            public void onStart(String... args) {
                startSpeak();                   
            }
        });
0

Source: https://habr.com/ru/post/1774017/


All Articles