Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Using Speech to Text

Published? true
FormatLanguage: WikiFormat

Problem:

How to get speech input and display it as text

Solution:

One of Android's unique features is native speech to text processing. This provides an alternative form of text input for the user, who in some situations might not have their hands readily available to type in information.

Discussion:

Android provides an easy API for using its built in voice recognition through the RecognizerIntent.

The example layout will be very simple. I've only included a TextView and a Button. The button will be used to launch the voice recognizer, and when results are returned they will be displayed in the TextView.

<?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/getSpeechButton"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:text="Press to begin voice recognition"
	></Button>
<TextView  
	android:id="@+id/speechText"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text=""
    />
</LinearLayout>

public class Main extends Activity {
	
    private static final int RECOGNIZER_RESULT = 1234;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button startSpeech = (Button)findViewById(R.id.getSpeechButton);
        startSpeech.setOnClickListener(new OnClickListener() {

        	@Override
	        public void onClick(View v) {
		    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
		                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech to text");
		     startActivityForResult(intent, RECOGNIZER_RESULT);						
		}
        	
        });
    }
    
    /**
     * Handle the results from the recognition activity.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RECOGNIZER_RESULT && resultCode == RESULT_OK) {
            ArrayList<String> matches = data.getStringArrayListExtra(
                    RecognizerIntent.EXTRA_RESULTS);
            
            TextView speechText = (TextView)findViewById(R.id.speechText);            
            speechText.setText(matches.get(0).toString());
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}

See Also:

http://developer.android.com/reference/android/speech/RecognizerIntent.html