First Android App | Step 9 | Speech Recognizer in Android

In this step, we are going to see how to integrate the Google's speech recognizer to capture voice and get the text conversion back to your activity.

In this case, the speech recognizer has been used on the Search tab as can be see below. There is a button next to searchView where we are integrating the speech recognizer.


Below is the YouTube video to explain how the integration was done.



Source Code

Changes in Search.java

1. Add setOnClickListener for audio button.

        buttonAudio.setOnClickListener(new OnClickListener() 
        {
            public void onClick(View v) 
            {
             Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                // Specify free form input
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
                intent.putExtra(RecognizerIntent.EXTRA_PROMPT,"Please start speaking");
                intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
                startActivityForResult(intent, 2); 
            }
        });

2. Add code in onActivityResult to retrieve results and populate the searchView.

@Override  
    public void onActivityResult(int requestCode, int resultCode, Intent data)  
    {  
        //this requestCode is for handling the barcode activity.       
        if(requestCode==1)  
        {  
         String barcode=data.getStringExtra("BARCODE");
         if (barcode.equals("NULL"))
         {
          //that means barcode could not be identified or user pressed the back button
          //do nothing 
         }
         else
         {
          search.setQuery(barcode, true);
          search.setIconifiedByDefault(false);
         }
        }
        
        //this requestCode is for speechRecognizer. Only this part of the code needs to be added for
        //the implementation of voice to text functionality. 
 
        if (requestCode == 2) {
            ArrayList results;
            results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            //Toast.makeText(this, results.get(0), Toast.LENGTH_SHORT).show();
            
            //if the name has an ' then the SQL is failing. Hence replacing them. 
            String text = results.get(0).replace("'","");
            search.setQuery(text, true);
         search.setIconifiedByDefault(false);
        }
          
    }

No comments:

Post a Comment