teaching machines

Voice recognition sans dialog box

October 13, 2011 by . Filed under public, reader animated.

Android provides a nice speech recognition system. Many examples show how you can push out an ACTION_RECOGNIZE_SPEECH intent to trigger an Activity that shows the listening status on a big dialog box. I wanted speech recognition without the dialog box and was able to do so with the following code:

public class BackgroundListenerTest extends Activity implements RecognitionListener {
  /** Text display */
  private TextView blurb;

  /** Parameters for recognition */
  private Intent recognizerIntent;

  /** The ear */
  private SpeechRecognizer recognizer;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.speech);

    blurb = (TextView) findViewById(R.id.blurb);

    recognizer = SpeechRecognizer.createSpeechRecognizer(this);
    recognizer.setRecognitionListener(this);

    recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "org.twodee.andytest");
    recognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
    recognizer.startListening(recognizerIntent);
  }

  @Override
  public void onBeginningOfSpeech() {
    blurb.append("[");
  }

  @Override
  public void onBufferReceived(byte[] arg0) {
  }

  @Override
  public void onEndOfSpeech() {
    blurb.append("] ");
  }

  @Override
  public void onError(int arg0) {
  }

  @Override
  public void onEvent(int arg0,
                      Bundle arg1) {
  }

  @Override
  public void onPartialResults(Bundle arg0) {
  }

  @Override
  public void onReadyForSpeech(Bundle arg0) {
    blurb.append("> ");
  }

  @Override
  public void onResults(Bundle bundle) {
    ArrayList<String> results = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    blurb.append(results.toString() + "\n");
    recognizer.startListening(recognizerIntent);
  }

  @Override
  public void onRmsChanged(float arg0) {
  }
}

The XML layout defines a TextView widget with ID blurb. In the manifest, I need to request RECORD_AUDIO permissions:

<uses-permission android:name="android.permission.RECORD_AUDIO" />