{"id":80,"date":"2013-07-02T20:54:44","date_gmt":"2013-07-02T20:54:44","guid":{"rendered":"https:\/\/code4reference.com\/?p=80"},"modified":"2023-10-01T13:34:27","modified_gmt":"2023-10-01T13:34:27","slug":"code4referencetutorial-on-android-voice-recognition-api","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=80","title":{"rendered":"Tutorial on Android Voice recognition Api"},"content":{"rendered":"<p>You may have heard about the \u201c<strong><em>Google Now\u00a0project\u201d<\/em><\/strong>\u00a0where you give the voice command and Android fetches result for\u00a0you. It recognizes your voice and converts it into the text or takes the appropriate action. Have you ever thought how is it done? If your answer is voice recognition API, then you are absolutly right. Recently while playing with Android voice recognition APIs, I found some interesting stuffs. APIs are really easy to use with application. Given below is a small tutorial on voice\/speech recognition API. The final application will look similar to that of application shown below. The application may not work on the Android Emulator because it doesn\u2019t support voice recognition. But the same can work on the phone. <a href=\"http:\/\/2.bp.blogspot.com\/-qiSzM4-2Anw\/UA46V3ALajI\/AAAAAAAAAmA\/yZn_hlMDTFI\/s1600\/voice-recognition-tutorial-example-2.png\"><img alt='voice-recognition-tutorial-example-2-9312583' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/voice-recognition-tutorial-example-2-9312583.png' \/><\/a><\/p>\n<p><strong>Project Information:<\/strong> Meta-data about the project.<\/p>\n<p><strong>Platform Version :<\/strong> Android API Level 15.<br \/>\n<strong>IDE :<\/strong> Eclipse Helios Service Release 2<br \/>\n<strong>Emulator :<\/strong> Android 4.1(API 16)<\/p>\n<p><strong>Prerequisite:<\/strong>\u00a0Preliminary\u00a0knowledge of Android application framework, and Intent.<\/p>\n<p>Voice recognition feature can be achieved by RecognizerIntent. Create an Intent of type RecognizerIntent and pass the extra parameters and start activity for the result. It basically starts the recognizer prompt customized by your extra parameters. Internally voice recognition\u00a0communicates with the server and gets the results. So you must provide the internet access permission for the application.\u00a0Android Jelly Bean(API level 16) doesn\u2019t \u00a0require internet connection to perform voice recognition.\u00a0 Once the voice recognition is done, recognizer returns value in \u00a0onActivityResult() method parameters.<br \/>\nFirst create project by<strong>\u00a0<em>Eclipse &gt; File&gt; New Project&gt;Android Application Project<\/em>.<\/strong>\u00a0The following dialog box will appear. Fill the required field, i.e Application Name, Project Name and Package. Now press the\u00a0<strong>next<\/strong> button.<\/p>\n<p><a href=\"http:\/\/1.bp.blogspot.com\/-jZdlwqbp27k\/UA46ibbvImI\/AAAAAAAAAmQ\/UY5uEqUxig0\/s1600\/Android-project-voice-recognition-3.png\"><img alt='android-project-voice-recognition-3-6292612' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/Android-project-voice-recognition-3-6292612.png' \/><\/a><\/p>\n<p>Once the dialog box appears, select the BlankActivity and click the\u00a0<strong><em>next<\/em><\/strong>\u00a0button.<\/p>\n<p><a href=\"http:\/\/2.bp.blogspot.com\/-gMqI4T_wmAw\/UA46gVS6uzI\/AAAAAAAAAmI\/PXJ6_fQ367I\/s1600\/Android-project-voice-recognition-2.png\"><img alt='android-project-voice-recognition-2-5313348' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/Android-project-voice-recognition-2-5313348.png' \/><\/a><\/p>\n<p>Fill the Activity Name and Layout file name in the dialog box shown below and hit the\u00a0<strong><em>finish<\/em><\/strong>\u00a0button.<\/p>\n<p><a href=\"http:\/\/2.bp.blogspot.com\/-z4RjN3wZIx4\/UA98ds0JwRI\/AAAAAAAAAm8\/RYno2VErHro\/s1600\/Android-project-voice-recognition-3.png\"><img alt='android-project-voice-recognition-3-6573382' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/Android-project-voice-recognition-3-6573382.png' \/><\/a><\/p>\n<p>This process will setup the basic project files. Now we are going to add four buttons in the\u00a0<strong><em>activity_voice_recognition.xml<\/em><\/strong>\u00a0file. \u00a0You can modify the layout file using either Graphical Layout editor or xml editor. The content of the file is shown below. As you may notice that we have attached <strong><em>speak<\/em><\/strong>() method with button in <strong><em>onClick<\/em><\/strong> tag. When the button gets clicked, the speak() method will get executed. We will define speak() in the main activity.<\/p>\n<pre>\n\n\n\n    \n\n    \n\n    \n\n    \n\n    \n\n\n<\/pre>\n<p>You may have noticed that the String constants are being accessed from the resource. Now add the string constants in <strong><em>string.xml<\/em><\/strong>. This file should look similar to the one shown below.<\/p>\n<pre>\n\n    VoiceRecognitionExample\n    Speak\n    Settings\n    Voice Recognition\n    Text Matches\n    No of Matches\n    Speech hint here\n    \n        1\n        2\n        3\n        4\n        5\n        6\n        7\n        8\n        9\n        10\n    \n\n<\/pre>\n<p>Now let\u2019s define the Activity class. This activity class,\u00a0with the help of\u00a0checkVoiceRecognition() method,\u00a0will\u00a0first\u00a0check whether the Voice recognition is available or not. If voice recognition feature is not available, then toast a message and disable the button. Speak() method is defined here which gets called once the speak button is pressed. In this method we are creating RecognizerIntent and passing the extra parameters. The code below has embedded comments which makes it easy to understand.<\/p>\n<pre>\npackage com.rakesh.voicerecognitionexample;\n\nimport java.util.ArrayList;\nimport java.util.List;\n\nimport android.app.Activity;\nimport android.app.SearchManager;\nimport android.content.Intent;\nimport android.content.pm.PackageManager;\nimport android.content.pm.ResolveInfo;\nimport android.os.Bundle;\nimport android.speech.RecognizerIntent;\nimport android.view.View;\nimport android.widget.AdapterView;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.ListView;\nimport android.widget.Spinner;\nimport android.widget.Toast;\n\npublic class VoiceRecognitionActivity extends Activity {\n private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;\n\n private EditText metTextHint;\n private ListView mlvTextMatches;\n private Spinner msTextMatches;\n private Button mbtSpeak;\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n  super.onCreate(savedInstanceState);\n  setContentView(R.layout.activity_voice_recognition);\n  metTextHint = (EditText) findViewById(R.id.etTextHint);\n  mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);\n  msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);\n  mbtSpeak = (Button) findViewById(R.id.btSpeak);\n  checkVoiceRecognition()\n }\n\n public void checkVoiceRecognition() {\n  \/\/ Check if voice recognition is present\n  PackageManager pm = getPackageManager();\n  List activities = pm.queryIntentActivities(new Intent(\n    RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);\n  if (activities.size() == 0) {\n   mbtSpeak.setEnabled(false);\n   mbtSpeak.setText(\"Voice recognizer not present\")\n   Toast.makeText(this, \"Voice recognizer not present\",\n     Toast.LENGTH_SHORT).show();\n  }\n }\n\n public void speak(View view) {\n  Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);\n\n  \/\/ Specify the calling package to identify your application\n  intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()\n    .getPackage().getName());\n\n  \/\/ Display an hint to the user about what he should say.\n  intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()\n    .toString());\n\n  \/\/ Given an hint to the recognizer about what the user is going to say\n  \/\/There are two form of language model available\n  \/\/1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases\n  \/\/2.LANGUAGE_MODEL_FREE_FORM  : If not sure about the words or phrases and its domain.\nintent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,\n    RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);\n\n  \/\/ If number of Matches is not selected then return show toast message\n  if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {\n   Toast.makeText(this, \"Please select No. of Matches from spinner\",\n     Toast.LENGTH_SHORT).show();\n   return;\n  }\n\n  int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()\n    .toString());\n  \/\/ Specify how many results you want to receive. The results will be\n  \/\/ sorted where the first result is the one with higher confidence.\n  intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);\n  \/\/Start the Voice recognizer activity for the result.\n  startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n  if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)\n\n   \/\/If Voice recognition is successful then it returns RESULT_OK\n   if(resultCode == RESULT_OK) {\n\n    ArrayList textMatchList = data\n    .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);\n\n    if (!textMatchList.isEmpty()) {\n     \/\/ If first Match contains the 'search' word\n     \/\/ Then start web search.\n     if (textMatchList.get(0).contains(\"search\")) {\n\n        String searchQuery = textMatchList.get(0);\n                                           searchQuery = searchQuery.replace(\"search\",\"\");\n        Intent search = new Intent(Intent.ACTION_WEB_SEARCH);\n        search.putExtra(SearchManager.QUERY, searchQuery);\n        startActivity(search);\n     } else {\n         \/\/ populate the Matches\n         mlvTextMatches\n      .setAdapter(new ArrayAdapter(this,\n        android.R.layout.simple_list_item_1,\n        textMatchList));\n     }\n\n    }\n   \/\/Result code for various error.\n   }else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){\n    showToastMessage(\"Audio Error\");\n   }else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){\n    showToastMessage(\"Client Error\");\n   }else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){\n    showToastMessage(\"Network Error\");\n   }else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){\n    showToastMessage(\"No Match\");\n   }else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){\n    showToastMessage(\"Server Error\");\n   }\n  super.onActivityResult(requestCode, resultCode, data);\n }\n \/**\n * Helper method to show the toast message\n **\/\n void showToastMessage(String message){\n  Toast.makeText(this, message, Toast.LENGTH_SHORT).show();\n }\n}\n<\/pre>\n<p>Here is the Android manifest file. You can see that \u00a0INTERNET permission\u00a0has been provided\u00a0to the application because of the voice recognizer\u2019s need to send the query to the server and get the result.<\/p>\n<pre>\n\n\n    \n    \n \n\n    \n\n        \n            \n                \n\n                \n            \n        \n    \n\n<\/pre>\n<p>Once you are done with coding then connect the phone with your system and hit the run button on Eclipse IDE. Eclipse will install and launch the application. You will see the following activities on your device screen.<\/p>\n<table>\n<tr>\n<td><a href=\"http:\/\/3.bp.blogspot.com\/-cEyDjq9Gfec\/UA46x3SsaUI\/AAAAAAAAAmg\/DpuN4u724lc\/s1600\/voice-recognition-tutorial-example-1.png\"><img alt='voice-recognition-tutorial-example-1-3390339' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/voice-recognition-tutorial-example-1-3390339.png' \/><\/a><\/td>\n<td><a href=\"http:\/\/4.bp.blogspot.com\/-H4hsE-k5AQ4\/UA46zc4jMCI\/AAAAAAAAAmo\/A_NeWdjuUGk\/s1600\/voice-recognition-tutorial-example-2.png\"><img alt='voice-recognition-tutorial-example-2-1004693' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/voice-recognition-tutorial-example-2-1004693.png' \/><\/a><\/td>\n<td><a href=\"http:\/\/2.bp.blogspot.com\/-KnWvwrsCuJM\/UA461lW0skI\/AAAAAAAAAmw\/N5TUcnDtW-Y\/s1600\/voice-recognition-web-search.png\"><img alt='voice-recognition-web-search-3880551' src='https:\/\/code4reference.com\/wp-content\/uploads\/2013\/07\/voice-recognition-web-search-3880551.png' \/><\/a><\/td>\n<\/tr>\n<\/table>\n<p>In the next tutorial, we will learn how to use the\u00a0new voice recognition API introduced in Android Jelly Bean(API level 16) along with the examples.<br \/>\nIf you are\u00a0interested\u00a0in the source code, then you can get it from <a href=\"http:\/\/github.com\/rakeshcusat\/Code4Reference\/tree\/master\/AndroidProjects\/VoiceRecognitionExample\">github<\/a>.<\/p>\n<h4>Your valuable comments are always welcomed. It will help to improve my post and understanding.<\/h4>\n<p><em>\u201cBy three methods we may learn wisdom: First, by reflection, which is noblest; Second, by imitation, which is easiest; and third by experience, which is the bitterest.\u201d<\/em><br \/>\nBy : Confucius<\/p>\n","protected":false},"excerpt":{"rendered":"<p>You may have heard about the \u201cGoogle Now\u00a0project\u201d\u00a0where you give the voice command and Android fetches result for\u00a0you. It recognizes your voice and converts it into the text or takes the appropriate action. Have you ever thought how is it done? If your answer is voice recognition API, then you are absolutly right. Recently while [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-80","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/80","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=80"}],"version-history":[{"count":1,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/80\/revisions"}],"predecessor-version":[{"id":351,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/80\/revisions\/351"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=80"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=80"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=80"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}