Add speech recognition to EditText in Android

Now a days many android application has the microphone icon on the right side of EditText. When you click on it, it will ask you to speak the words you want to enter into the EditText. After you speak the word to that dialog it will automatically enter those words into the EditText. Here is the screenshot for that.

speech recognition in android

speech recognition in android

Now to open this dialog, you need to add the below code to your any of the button’s click listener.

int REQUEST_CODE = 1;
String DIALOG_TEXT = "Speech recognition demo";
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, DIALOG_TEXT);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, 
                   RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, REQUEST_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
startActivityForResult(intent, requestCode);

Now when you click the button this dialog will be open and you can speak to it. Then it will store your speech and return it to you in onActivityResult method as String. Check the following code for it.

String resultSpeech = "";
@Override
protected void onActivityResult(int requestCode, int resultcode, Intent intent) {
    super.onActivityResult(requestCode, resultcode, intent);
    ArrayList<String> speech;
    if (resultcode == RESULT_OK) {  
        if (requestCode == REQUEST_CODE) {
            speech = intent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            resultSpeech = speech.get(0);
            //you can set resultSpeech to your EditText or TextView
        }
    }
}

Post your queries or questions in comment.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s