Voice Recognition Activity In Android Programming

This example shows how to use voice recognition API in android. The application may not work on the Android Emulator because it doesn’t support voice recognition. But the same can work on the phone.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it VoiceRecognitionActivity.

2.) Write following into main.xml:

 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/etTextHint"
android:gravity="top"
android:inputType="textMultiLine"
android:lines="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/etSearchHint"/>

<Button
android:id="@+id/btSpeak"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="speak"
android:padding="@dimen/padding_medium"
android:text="@string/btSpeak"
tools:context=".VoiceRecognitionActivity" />

<Spinner
android:id="@+id/sNoOfMatches"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/saNoOfMatches"
android:prompt="@string/sNoOfMatches"/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/tvTextMatches"
android:textStyle="bold" />

<ListView
android:id="@+id/lvTextMatches"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

 

 

3.) Write following into strings.xml:

 

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">VoiceRecognitionActivity</string>
<string name="hello_world">Hello world!</string>
<string name="menu_settings">Settings</string>
<string name="btSpeak">Speak</string>
<string name="tvTextMatches">Text Matches</string>
<string name="sNoOfMatches">No of Matches</string>
<string name="etSearchHint">Speech hint here</string>
<string-array name="saNoOfMatches">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
</string-array>
</resources>

 

 

4.) Create and write following into values/dimens.xml:

 

<resources>

<dimen name="padding_small">8dp</dimen>
<dimen name="padding_medium">8dp</dimen>
<dimen name="padding_large">16dp</dimen>

</resources>

 

 

5.) Write following into manifest file:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.voicerecognitionactivity"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="16" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.voicerecognitionactivity.VoiceRecognitionActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

 

 

6.) Run for output.

Steps:

1.) Create a project named VoiceRecognitionActivity and set the information as stated in the image.

Build Target: Android 4.0
Application Name: VoiceRecognitionActivity
Package Name: com. example. VoiceRecognitionActivity
Activity Name: VoiceRecognitionActivity
Min SDK Version: 4.0

2.) Open VoiceRecognitionActivity.java file and write following code there:

 

package com.example.voicerecognitionactivity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class VoiceRecognitionActivity extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;

private EditText metTextHint;
private ListView mlvTextMatches;
private Spinner msTextMatches;
private Button mbtSpeak;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
metTextHint = (EditText) findViewById(R.id.etTextHint);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
msTextMatches = (Spinner) findViewById(R.id.sNoOfMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
}

public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}

public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Specify the calling package to identify your application
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());

// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, metTextHint.getText()
.toString());

// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);

// If number of Matches is not selected then return show toast message
if (msTextMatches.getSelectedItemPosition() == AdapterView.INVALID_POSITION) {
Toast.makeText(this, "Please select No. of Matches from spinner",
Toast.LENGTH_SHORT).show();
return;
}

int noOfMatches = Integer.parseInt(msTextMatches.getSelectedItem()
.toString());
// Specify how many results you want to receive. The results will be
// sorted where the first result is the one with higher confidence.

intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, noOfMatches);

startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)

//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {

ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

if (!textMatchList.isEmpty()) {
// If first Match contains the 'search' word
// Then start web search.
if (textMatchList.get(0).contains("search")) {

String searchQuery = textMatchList.get(0).replace("search",
" ");
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, searchQuery);
startActivity(search);
} else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
textMatchList));
}

}
//Result code for various error.
}else if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}

 

 

3.) Compile and build the project.

Output

Leave a Comment:

13 comments
rahul says February 28, 2013

good tutorials

Reply
rahul says February 28, 2013

good site….

Reply
Mehbubul Hasan AL- Quvi says March 6, 2013

Will u pls give me a download link for this project, I want to download this project because i’m not so good in coding nd i found some errors,
plss….

Reply
kshama jain says March 30, 2013

i am getting the error “unfortunately,voicerecognitionactivity has stopped”.
in logcat, this error is in intent (line no. 80)

Reply
eshaan says April 4, 2013

problem parsing the package

Reply
imam nur says April 18, 2013

Thanks for your tutorial sir.

I want to ask you about around spinner too.
I have two spinner, and the spinner is contained in the data that will be called to another activity to do calculations. I would like to ask how to send data on spinner to the activity?

I’ve been looking everywhere, but nobody discussed it specifically sir.
please your help sir.. 🙂

Thanks before.
Warm Regards,
Imam Nur

Reply
radu says April 24, 2013

Hi Sushant ! Thanks for this grate tutorial it works perfect, but i have a question about htis line

String searchQuery = textMatchList.get(0).replace(“search”,

in this case the app will take the first position from the list and do smth, I am interested in showing the list of possible matches and then when you click on one of them will send you to the web . so i am guessing that in stead of get(0) use smth liek getPosition , i have tried but is not working .. Do you have suggestions ?

Reply
Levan says May 31, 2013

Tell me how the application should work, I do not understand. I press the button and say, well, it does not give me anything.

Reply
Levan says May 31, 2013

Please tell me more, I said the word, it has translated into a string that is displayed in the listview, if I want to get my line and process it, for example, said the red and the background changed to red …

I think in this part of the need to dig.

else {
// populate the Matches
mlvTextMatches
.setAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1,
textMatchList));
}

Reply
Shamili says June 23, 2013

R.Java file cannot be generated for this program
what can i do for this

Reply
prasanth says September 24, 2013

i make this same code and compiled it. it runs fine..but its not opens the websearch… Why?? What is the problem?? All permission are given and its correct..

Reply
bala says September 24, 2013

i make this same code and compiled it. it runs fine..but its not opens the websearch… Why?? What is the problem?? All permission are given and its correct..

Reply
prasanth says September 24, 2013

In this code websearch is not opening…

Reply
Add Your Reply