Sunday, July 21, 2013

Make your next Android app a good listener

This tutorial demonstrates how simple it is to use the Android Speech to Text API.



Last week I wrote a post on how easy it is to .It's easy because Google's speech API does all the heavy lifting for us. But the API doesn't stop at speaking text aloud -- it also allows you to speak to the device and then translates those voice commands into text an application can use.




This tutorial demonstrates how to add voice recognition to your next Android app. Feel free to follow along or and import it directly into Eclipse.



1.Create a new Android project in Eclipse.Target Android 2.2 or higher.

2.In the /res/layout directory, modify the activitymain.xml file to include a text view and an image button.



activitymain.xml



3.In the /src folder, open MainActivity.java. The on create override should look familiar; it simply wires up the button.



MainActivity.java

package com.authorwjf.talk2me;



import java.util.ArrayList;



import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.speech.RecognizerIntent;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.TextView;

import android.widget.Toast;



public class MainActivity extends Activity implements OnClickListener {



protected static final int REQUESTOK = 1;



protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activitymain);

findViewById(R.id.button1).setOnClickListener(this);4.The on click handler is responsible for firing off the voice intent.



public void onClick(View v) {

Intent i = new Intent(RecognizerIntent.ACTIONRECOGNIZESPEECH);

i.putExtra(RecognizerIntent.EXTRALANGUAGEMODEL, "en-US");

try {

startActivityForResult(i, REQUESTOK);

} catch (Exception e) {

Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTHLONG).show();



5.When the intent calls back, we display the transcribed text.



protected void onActivityResult(int requestCode, int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode==REQUESTOK &

((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));



Load the resulting APK to your Android device via a USB cable and try it out.



If your device isn't running JellyBean, you will need Internet connectivity for the voice input to work.If your device is running JellyBean, you can go to Settings | Language & Input | Voice Search and download the offline speech recognition pack.
Full Post

No comments:

Post a Comment