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.

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_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 = "";
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.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s