如何在 Text To Speech 停止后立即启动语音识别。

How to start Speech Recognition as Soon the Text To Speech stops.

我想在 Text To Speech 停止后立即启动语音识别。 以下是我采取的步骤。

第 1 步:初始化语音识别。

    mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
    mSpeechRecognizer.setRecognitionListener(recognitionListener);

    mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
            Locale.getDefault());

步骤 2:Initialize 文字转语音。

    TextToSpeech myTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
        @Override
        public void onInit(int status) {
            if(myTTS.getEngines().size() == 0){
                Toast.makeText(Robo.this,"No Engines Installed",Toast.LENGTH_LONG).show();
            }else{


                if (status == TextToSpeech.SUCCESS){
                    //Toast.makeText(MainActivity.this,"Status working.",Toast.LENGTH_LONG).show();
                    //message = "How may i help you.";
                    myTTS.setLanguage(Locale.US);
                    ttsInitialized();
                    speak("what is your name.");
                }

            }
        }
    });

步骤 3:Initialize 检查语音是否完成的话语监听器。

    myTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
        @Override
        public void onStart(String utteranceId) {

        }

        @Override
        public void onDone(String utteranceId) {

            //btn.performClick();
            myTTS.shutdown();
            mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
        }

        @Override
        public void onError(String utteranceId) {

        }
    });

在onDone()方法中mSpeechRecognizer.startListening(mSpeechRecognizerIntent);用于启动语音识别,但不启动语音识别。 请查看问题。

onDone 方法引用特定的话语。这意味着如果您多次(连续)调用 mTTS.speak 方法,则每次都会调用 onDone。这显然会对您要实现的目标造成严重问题。

当我必须在 TTS 完成后执行操作时,我会创建一个变量,如 lastUtteranceId,将其设置为最后排队的话语,并在 onDone 中检查匹配项,如:

if (utteranceId.equals(lastUtteranceId) {
   // TTS finished talking...
}

另外,在那里调用 shutdown 似乎不是个好主意。您应该在 activity 的 onDestroy 方法中调用它。

最后,我认为 onDone 在后台线程上运行,而 startListening 需要在主线程上运行,所以也要检查一下。

正如@Regulus 所说,我添加了一个处理程序并且它起作用了。

    @Override
    public void onDone(String utteranceId) {

        Handler mainHandler = new Handler(Looper.getMainLooper());
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                } // This is your code
            };
            mainHandler.post(myRunnable);

    }