Wednesday, January 18, 2012

How to implement Voice Recognition in android application


How to implement Voice Recognition in android application

Here is the tutorial to create android application which will convert voice to text, and then that text you can use where ever you want.

First create the Android project and follow the below steps [I had give VoiceToText as project name]-

1. No changes are required in AndroidManifest.xml file. Just for your reference below is my AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.voicetotext"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".VoiceToTextActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>


2.  Create UI which will have Button and list view, following is my main.xml file. [If you want you can create new file otherwise use the default main.xml file]


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"> 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="4dip"
        android:text="Click button and start speaking" />

    <Button android:id="@+id/speakBtn"
        android:layout_width="fill_parent"
        android:onClick="speakButtonClicked"
        android:layout_height="wrap_content"
        android:text="Hit Me!" />

    <ListView android:id="@+id/resultList"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />
 </LinearLayout>


3. Now need to code your main activity class, once user hit the Hit Me! button it will listen and translate voice to text and display that into resultList list view. Following is my main activity class -

package com.voicetotext;

import android.app.Activity;
import android.os.Bundle;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;


public class VoiceToTextActivity extends Activity {
    private static final int REQUEST_CODE = 1234;
    private ListView resultList;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button speakBtn = (Button) findViewById(R.id.speakBtn);

        resultList = (ListView) findViewById(R.id.resultList);

        // Disable button if no recognition service is present
        PackageManager pm = getPackageManager();
        List RecognizerActivities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        if (RecognizerActivities.size() == 0)
        {
            speakBtn.setEnabled(false);
            speakBtn.setText("Recognizer unavailable!!!");
        }
    }

    /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice To Text Demo…");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
        {
            // Populate the resultList with the String values the recognition engine thought it heard
            ArrayList matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            resultList.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
                    matches));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

Now you can run this application and speak the word or sentences, it will start converting those words into text and later you can use those text as a command to perform any tasks.

Note: This will not work on emulator, you will need actual device to test this application.

No comments:

Post a Comment