android voice recognition stop

808 views Asked by At

Is it possible to stop the intent which is listening for the users speech? For example I have this listener:

  @Override
            public boolean onTouch(View v, MotionEvent event) {
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                switch(event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es");
                        intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
                        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
                        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
                        return true;
                    case MotionEvent.ACTION_UP:
                        //Code to stop listening user speech

                        return true; 
            }

My idea is that the user must keep pressing a specific button so the app listen the speech, like the microphone button in Whatsapp.

EDIT

I think I have already tried what @brandall tells me to do. Here is the modification of the code:

  public boolean onTouch(View v, MotionEvent event) {
                    SpeechRecognizer speechRecognizer = createSpeechRecognizer(context);
                    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                    switch(event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "es");
                            intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
                            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
                            intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
                            speechRecognizer.startListening(intent);
                            startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
                            return true; 
                        case MotionEvent.ACTION_UP:
                            speechRecognizer.stopListening();
                            return true;
                    }
                    return false;
                }

            });
0

There are 0 answers