Voice Recognition API example changes - android

I'm working with the voice recognition API with the code that is already provided within the API examples the feature that I want in the same activity example is:
A) that it works even when my phone is not used that is when the screen is locked.
B) If the googleAPI doesn't find the word it shows a dialog saying cancel/speak again then code selects speak again by itself ,how to go about.
Here's the code:
package com.wwwww.and;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Sample code that invokes the speech recognition intent API.
*/
public class VoiceRecognition extends Activity implements OnClickListener {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Inflate our UI from its XML layout description.
setContentView(R.layout.voice_recognition);
// Get display items for later interaction
Button speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
startVoiceRecognitionActivity();
}
/**
* Handle the click on the start recognition button.
*/
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
//startVoiceRecognitionActivity();
}
}
/**
* Fire an intent to start the speech 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, " VoiceRecognition Service");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}

A) that it works even when my phone is not used that is when the screen is locked.
You need to implement the speech recognition in a service.
B) If the googleAPI doesn't find the word it shows a dialog saying cancel/speak again then code selects speak again by itself ,how to go about.
Change your onActivityResult to the one below
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches;
if (data != null)
{
matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
}
if (data == null || matches.size() == 0)
{
startVoiceRecognitionActivity();
}
else
{
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
}
else
{
startVoiceRecognitionActivity();
}
}
super.onActivityResult(requestCode, resultCode, data);
}

Related

How to detect if there is a sound in android?

I am new to android development. Ive to make an application which detects sound and plays music. I have already taken care of music playing part but the problem is that I don't understand how to put a condition to check that whether there is even a sound or not
Im using eclipse and android API 20 and voice recognition intent. Kindly look at the following code.
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;
/**
* A very simple application to handle Voice Recognition intents
* and display the results
*/
public class MainActivity extends Activity
{
private static final int REQUEST_CODE = 1234;
private ListView wordsList;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recog);
Button speakButton = (Button) findViewById(R.id.speakButton);
wordsList = (ListView) findViewById(R.id.list);
// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0)
{
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
else
{startVoiceRecognitionActivity();}
}
/**
* Handle the action of the button being clicked
*/
/**
* 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 recognition 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 wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Speech to Text Conversion - NOt getting desired output

I want to do speech to text conversion for one of my project. But I am not getting the desired result. Can you pls let me know what should I modify for the code to work?
package com.example.speechtotext;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected static final int RESULT_SPEECH = 1;
private ImageButton btnSpeak;
private TextView txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtText = (TextView) findViewById(R.id.txtText);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
try {
startActivityForResult(intent, RESULT_SPEECH);
txtText.setText("");
} catch (ActivityNotFoundException a) {
Toast t = Toast.makeText(getApplicationContext(),
"Opps! Your device doesn't support Speech to Text",
Toast.LENGTH_SHORT);
t.show();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SPEECH: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> text = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtText.setText(text.get(0));
}
break;
}
}
}
}
There are no compilation or runtime errors. As soon as I click the "Speak Now" button on the emulator, it says that Oops!! Your device doesn't support speech to text. I tried to install the .apk in my android and check it.It throws a pop up msg that "Connection Problem" with a warning mark and two buttons on the bottom for "Speak again " and "cancel".
Pls tell me what is the problem.
public class VoiceRecognition extends Activity implements OnClickListener {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recognition);
Button speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
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, "Speech recognition demo");
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Your device needs to have the Intent which will be able to recognise voice. If such an Intent doesn't exist, you get the error you mentioned.
Try installing "Google Voice Search" app from the play store.

Recognizer Intent not able to define its constants

I am using the activity, voicerecognition.java, provided by Google to allow the user to choose a language, talk into the handset, and view what they have just said. It works when I take out all the language constants, but when I put the language options in, I get errors.
For example:
The method getVoiceDetailsIntent(VoiceRecognition) is undefined for the type
EXTRA_SUPPORTED_LANGUAGES cannot be resolved or is not a field
EXTRA_LANGUAGE_PREFERENCE cannot be resolved or is not a field
The method run() of type new Runnable(){} must override a superclass method
I thought I might just need to update the SDK or something but everything is up to date. I have no idea what is wrong since I copied the activity exactly as is on the link provided.
package com.sample.voicerecog;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class VoiceRecognition extends Activity implements OnClickListener {
private static final String TAG = "VoiceRecognition";
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
private Handler mHandler;
private Spinner mSupportedLanguageView;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
// Inflate our UI from its XML layout description.
setContentView(R.layout.voice_recognition);
// Get display items for later interaction
Button speakButton = (Button) findViewById(R.id.btn_speak);
mList = (ListView) findViewById(R.id.list);
mSupportedLanguageView = (Spinner) findViewById(R.id.supported_languages);
// Check to see if a recognition activity is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
speakButton.setOnClickListener(this);
} else {
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
// Most of the applications do not have to handle the voice settings. If the application
// does not require a recognition in a specific language (i.e., different from the system
// locale), the application does not need to read the voice settings.
refreshVoiceSettings();
}
/**
* Handle the click on the start recognition button.
*/
public void onClick(View v) {
if (v.getId() == R.id.btn_speak) {
startVoiceRecognitionActivity();
}
}
/**
* Fire an intent to start the speech recognition activity.
*/
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
// Display an hint to the user about what he should say.
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speech recognition demo");
// Given an hint to the recognizer about what the user is going to say
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// Specify how many results you want to receive. The results will be sorted
// where the first result is the one with higher confidence.
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
// Specify the recognition language. This parameter has to be specified only if the
// recognition has to be done in a specific language and not the default one (i.e., the
// system locale). Most of the applications do not have to set this parameter.
if (!mSupportedLanguageView.getSelectedItem().toString().equals("Default")) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
mSupportedLanguageView.getSelectedItem().toString());
}
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the recognition activity.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
// Fill the list view with the strings the recognizer thought it could have heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
private void refreshVoiceSettings() {
Log.i(TAG, "Sending broadcast");
sendOrderedBroadcast(RecognizerIntent.getVoiceDetailsIntent(this), null,
new SupportedLanguageBroadcastReceiver(), null, Activity.RESULT_OK, null, null);
}
private void updateSupportedLanguages(List<String> languages) {
// We add "Default" at the beginning of the list to simulate default language.
languages.add(0, "Default");
SpinnerAdapter adapter = new ArrayAdapter<CharSequence>(this,
android.R.layout.simple_spinner_item, languages.toArray(
new String[languages.size()]));
mSupportedLanguageView.setAdapter(adapter);
}
private void updateLanguagePreference(String language) {
TextView textView = (TextView) findViewById(R.id.language_preference);
textView.setText(language);
}
/**
* Handles the response of the broadcast request about the recognizer supported languages.
*
* The receiver is required only if the application wants to do recognition in a specific language.
*/
private class SupportedLanguageBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, final Intent intent) {
Log.i(TAG, "Receiving broadcast " + intent);
final Bundle extra = getResultExtras(false);
if (getResultCode() != Activity.RESULT_OK) {
mHandler.post(new Runnable() {
#Override
public void run() {
showToast("Error code:" + getResultCode());
}
});
}
if (extra == null) {
mHandler.post(new Runnable() {
#Override
public void run() {
showToast("No extra");
}
});
}
if (extra.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES)) {
mHandler.post(new Runnable() {
#Override
public void run() {
updateSupportedLanguages(extra.getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES));
}
});
}
if (extra.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE)) {
mHandler.post(new Runnable() {
#Override
public void run() {
updateLanguagePreference(
extra.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE));
}
});
}
}
private void showToast(String text) {
Toast.makeText(VoiceRecognition.this, text, 1000).show();
}
}
}
Any help is appreciated
It appears that your project is at a lower API level than level 8. To fix this, if you are using Eclipse, right click on your project and click properties. Choose Android from the menu on the left, and select a different project build target. If you don't find one at level 8 or higher, click on Window -> Android SDK Manager and install one. You can see what features of RecognizerIntent are available at the various API levels here.

Zxing when qr code is scanned it reverts to menu

I have the zxing library imported into my project and the scanner works like a charm but when i scan a qr code it says Qr code found and goes back to the menu i had set up is there any way to show the result and set it to open the url
package com.Qrgolf.App;
import java.util.regex.Pattern;
import com.google.zxing.Result;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button scan = (Button) findViewById(R.id.SCANBUTTON);
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);
}
});
};
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}
}
You should consider going back to your old questions and accepting answers if they were correct.
Also you need to change the onActivityResult() method to do whatever it is that you want to do with the resulting String from the QR.
here is an example:
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == 0) {
if (resultCode == RESULT_OK) {
String contents = intent.getStringExtra("SCAN_RESULT");
String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
// Handle successful scan
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(android.net.Uri.parse(contents));
startActivity(intent);
} else if (resultCode == RESULT_CANCELED) {
// Handle cancel
}
}
}

Voice Input to Populate Edit Text in android?

I am working on voice input in android. I used the sample from
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/VoiceRecognition.html
And while testing on Xperia X10, I got the "Speak now" dialog but before I input some voice it gets closed. I am trying to implement voice search e.g. If voice input is James Bond then I want to populate the James in first name Edit Text and Bond in Last name Edit Text. Which will search in database for the name. But while trying to use the API Demo sample, its not working. May be I am missing something. Will anybody post any sample for voice input rather than ApiDemos sample.
Thanks in advance.
You can use the following code for voice recognition. For a complete tutorial for voice recognition, Click Here.
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;
/**
* A very simple application to handle Voice Recognition intents
* and display the results
*/
public class VoiceRecognitionDemo extends Activity
{
private static final int REQUEST_CODE = 1234;
private ListView wordsList;
/**
* Called with the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.voice_recog);
Button speakButton = (Button) findViewById(R.id.speakButton);
wordsList = (ListView) findViewById(R.id.list);
// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0)
{
speakButton.setEnabled(false);
speakButton.setText("Recognizer not present");
}
}
/**
* 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 recognition 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 wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Categories

Resources