Exploring Voice Recognition

Android 1.5 includes a voice-recognition framework, and one of its popular toys is the Recognizerlntent class. The activity class in Listing 12-5 demonstrates this intent.

Listing 12-5. Using the RecognizerIntent import java.util.List;

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.speech.Recognizerlntent;

import android.util.Log;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class RecognizeSpeechActivity extends Activity {

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

Button btn = (Button)findViewByld(R.id.btn);

btn.setOnClickListener(new OnClickListener(){

^Override public void onClick(View v) {

startVoiceRecognition();

public void startVoiceRecognition() {

Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); startActivityForResult(intent, 0);

^Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data);

if(requestCode==0 && resultCode == Activity.RESULT_OK) {

List<String> text = data.getStringArrayListExtra(*-RecognizerIntent.EXTRA_RESULTS);

// do something with the result

// main.xml layout file

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<Button android:id="@+id/btn"

android:text="Speech Recognition" android:layout_width="wrap_content" android:layout_height="wrap_content" />

</LinearLayout>

Listing 12-5 displays a button in the UI that is meant to trigger the launching of the intent. In the click-handler method, the startVoiceRecognition() method is called. This method creates an intent with the action RecognizerIntent.ACTION_RECOGNIZE_SPEECH and then passes that to startActivityForResult(). This launches the speech-recognition activity, which prompts the user for speech. After the user submits speech data, the speech-recognition activity passes the data through a speech-recognizer component. The result of the activity is sent to the onActivityResult method, as shown.

That's obviously a lot of functionality for very little coding. It gets better. The framework also contains an intent action that executes a web search based on the result of the speech recognizer and displays the findings. Very powerful. You can try this by setting the intent action to

RecognizerIntent.ACTION_WEB_SEARCH

Note that because the preceding action will need to go to the Internet, you will need to add the Internet permission (<uses-permission android:name="android.permission. INTERNET"/>) to your AndroidManifest.xml file.

Now let's move on and discuss the input-method framework.

0 0

Post a comment