speech recognition gets unknown issue in android - android

I m trying to make an app in which when a call comes to the phone by using android tts it will speech the contact name of calling person(do you want to attend?). according to the reply of user the call should attend or end. in which i always getting a problem with the speech recognition(showing unknown problem) here i m giving my code, can any one help me to solve the issue.i was struck on this since last few days,any help will be appreciable..
public class myPhoneStateChangeListener extends PhoneStateListener
{
speechcontact clsspcntct = new speechcontact();
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
if (state == TelephonyManager.CALL_STATE_RINGING)
{
String phoneNumber = incomingNumber;
String ContactName = objUtility.getContactName2(context,phoneNumber);
mAudioManager.getStreamVolume(AudioManager.STREAM_RING);
mAudioManager.setStreamMute(AudioManager.STREAM_RING, true);
speakWords(ContactName);
}
if(state == TelephonyManager.CALL_STATE_IDLE && ph_state==1)
{
mAudioManager.setStreamMute(AudioManager.STREAM_RING, false);
}
}
#Override
public void onInit(int initStatus)
{
if (initStatus == TextToSpeech.SUCCESS) {
if(myTTS.isLanguageAvailable(Locale.ENGLISH)==TextToSpeech.LANG_AVAILABLE)
myTTS.setLanguage(Locale.ENGLISH);
}
else if (initStatus == TextToSpeech.ERROR) {
Log.d("speech log", "Sorry! Text To Speech failed...");
}
}
public void speakWords(String speech)
{
myTTS.speak("you have call from"+speech+"do you want to attend",TextToSpeech.QUEUE_FLUSH, null);
new Timer().schedule(new TimerTask() {
#Override
public void run()
{
startVoiceRecognitionActivity();
}
}, 5000);
}
public void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
try
{
startActivityForResult(intent, REQUEST_CODE);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(getApplicationContext(),"Ops! Your device doesn't support Speech to Text",Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
String spch = data.getStringExtra(RecognizerIntent.EXTRA_RESULTS);
if (spch.contains("Yes"))
{
// do smthing
}
else if(spch.contains("No"))
{
// do smething
}
}
super.onActivityResult(requestCode, resultCode, data);
}

The problem is that you are adding FLAG_ACTIVITY_NEW_TASK to your intent which according to the documentations:
This flag can not be used when the caller is requesting a result from the activity being launched.
and you are using it with startActivityForResult , removing
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
from your code fixes the issue.

I have an app that do what you want, it works fine on 2.3 to 4.0.
On jelly Bean does not work. Google made changes and looks like Jelly Bean stop
the voice recognition during the phone ringing.
So if you are testing on Jelly bean, try your code on another device.

Related

How do I hide the speechRecogniser activity behind the main activity?

I am trying to hide the speech recogniser dialog that shows up saying "speak now" and written google as the title ,whenever i call it for passing some voice command. I don't want it to show up. Instead I want it to work in teh background so that the user cannot see it. What should be the correct way to do it?
public void getSpeechInput(View view) {
getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, 10);
} else {
Toast.makeText(this, "Your Device Don't Support Speech Input", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10:
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txvResult.setText(result.get(0));
String str = txvResult.getText().toString();
if(str.equals("lights on")){
Toast.makeText(MainActivity.this,
"matched", Toast.LENGTH_LONG).show();
count[0]=1;
turnOnFlash();
}
else if(str.equals("lights off")){
Toast.makeText(MainActivity.this,
"didnt", Toast.LENGTH_LONG).show();
count[0]=0;
turnOffFlash();
}
}
break;
}
}
I tried using this but it didn't work:-
getWindow().getDecorView().setBackgroundResource(android.R.color.transparent);
Try this. This listener catches the events and you can process them accordingly.
SpeechRecognizer recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(new RecognitionListener()
{
//Do whatever you want
});

Google speech recognation listener dont listen

Hello am running google speech recognizing service but it stops listening after seconds how can i restart it or make it loop
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(getApplication());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,getPackageName());
SpeechRecognitionListener listener = new SpeechRecognitionListener();
mSpeechRecognizer.setRecognitionListener(listener);
CountDownTimer mTimer = new CountDownTimer(1500, 500) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
Log.d("Speech", "Timer.onFinish: Timer Finished, Restart recognizer");
//mSpeechRecognizer.cancel();
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
}
};
mTimer.start();
Remove your CountdownTimer. Put this in a method and when you want to start listening call the method.
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"Speech not supported on your device",
Toast.LENGTH_SHORT).show();
}
Speech output can be got in the onActivitySpeech method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE_SPEECH_INPUT) {
if (resultCode == RESULT_OK && data != null) {
//Handle the output
}
}
}

How to get the result of voice recognition on EditBox?

I know there is like a ton topic and question regarding Voice Recognition and my question might be a stupid one too. but please bear with me guys.
I need to get the result of the speech recognition into an (Editable Text Box) instead of (Array List), the editable text box to allow the user to edit the result , just like a memo.
I found some questions like mine but I could not understand ,I am still a beginner comparing to you guys .
This is the code :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private ListView mlvTextMatches;
private Button mbtSpeak;
private Button reButton;
private EditText result;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
result = (EditText) findViewById(R.id.out_text);
mlvTextMatches = (ListView) findViewById(R.id.lvTextMatches);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
mlvTextMatches .setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,textMatchList));
}
}
//Result code for various error.
{
} if(resultCode == RecognizerIntent.RESULT_AUDIO_ERROR){
showToastMessage("Audio Error");
}else if(resultCode == RecognizerIntent.RESULT_CLIENT_ERROR){
showToastMessage("Client Error");
}else if(resultCode == RecognizerIntent.RESULT_NETWORK_ERROR){
showToastMessage("Network Error");
}else if(resultCode == RecognizerIntent.RESULT_NO_MATCH){
showToastMessage("No Match");
}else if(resultCode == RecognizerIntent.RESULT_SERVER_ERROR){
showToastMessage("Server Error");
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Helper method to show the toast message
**/
void showToastMessage(String message){
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
This is the code after editing :
public class AVRScreen extends Activity {
private static final int VOICE_RECOGNITION_REQUEST_CODE = 1001;
private Button mbtSpeak;
private Button reButton;
private EditText myEditText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vr_screen);
Toast.makeText(this, "Press Speak! to Start Speeking",
Toast.LENGTH_LONG).show();
myEditText = (EditText) findViewById(R.id.out_text);
mbtSpeak = (Button) findViewById(R.id.btSpeak);
reButton = (Button)findViewById(R.id.Replay1);
reButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startActivity(new Intent(v.getContext(),KeyBoard.class));
}
});
checkVoiceRecognition();
}
public void checkVoiceRecognition() {
// Check if voice recognition is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
mbtSpeak.setEnabled(false);
mbtSpeak.setText("Voice recognizer not present");
Toast.makeText(this, "Voice recognizer not present",
Toast.LENGTH_SHORT).show();
}
}
public void speak(View view) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass()
.getPackage().getName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
//Start the Voice recognizer activity for the result.
startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
//If Voice recognition is successful then it returns RESULT_OK
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
myEditText.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// myEditText.append(match + "\n"); // or whatever separator you want
// }
}
}
the second try is :
} else {
// populate the Matches
//myEditText.setText(textMatchList.toString());
// if the above does not look good
for (String match : textMatchList) {
myEditText.append(match + "\n"); // or whatever separator you want
}
}
}
if(resultCode == RESULT_OK) {
ArrayList<String> textMatchList = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (textMatchList.get(0).contains("search")) {
} else {
// populate the Matches
result.setText(textMatchList.toString());
// if the above does not look good
// for (String match : textMatchList) {
// result.append(match + "\n"); // or whatever separator you want
// }
}

Text to Speech Android

I am trying to create a Text to Speech app that will remember the last sentence or part of the sentence after a comma where it was when the app is paused. Below is my code.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pitch = (EditText) findViewById(R.id.pitch);
words = (EditText) findViewById(R.id.wordsToSpeak);
words.setText("This message is intended only for the use of the individual or entity to which it is addressed and may contain information that is privileged, confidential or exempt from disclosure by law.");
speakBtn = (Button) findViewById(R.id.speak);
// Check to be sure that TTS exists and is okay to use
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, REQ_TTS_STATUS_CHECK);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQ_TTS_STATUS_CHECK) {
switch (resultCode) {
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// TTS is up and running
mTts = new TextToSpeech(this, this);
Log.v(TAG, "Pico is installed okay");
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
// missing data, install it
Log.v(TAG, "Need language stuff: " + resultCode);
Intent installIntent = new Intent();
installIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
default:
Log.e(TAG, "Got a failure. TTS apparently not available");
}
} else {
// Got something else
}
}
#Override
public void onInit(int status) {
// Now that the TTS engine is ready, we enable the button
if (status == TextToSpeech.SUCCESS) {
speakBtn.setEnabled(true);
mTts.setOnUtteranceCompletedListener(this);
}
}
public void doSpeak(View view) {
mTts.setPitch(new Float(pitch.getText().toString()));
StringTokenizer st = new StringTokenizer(words.getText().toString(),
",.");
while (st.hasMoreTokens()) {
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID,
String.valueOf(uttCount++));
mTts.speak(st.nextToken(), TextToSpeech.QUEUE_ADD, params);
}
// mTts.speak(words.getText().toString(), TextToSpeech.QUEUE_ADD, null);
};
#Override
public void onPause() {
super.onPause();
// if we're losing focus, stop talking
if (mTts != null)
mTts.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
mTts.shutdown();
}
#Override
public void onUtteranceCompleted(String utteranceId) {
Log.v(TAG, "Got completed message for uttId: " + utteranceId);
lastUtterance = Integer.parseInt(utteranceId);
}
}
I am able to get get the android to speak and keep track of the token that it last spoke. However, I am not sure how to resume where it last left off when you press the speakBtn. Is there anyway to go back to a certain token within a tokenizer if all the tokens were not successfully read out loud?
How about:
for(int i=0; i<successfulUtterances; ++i)
tokenizer.nextToken();
String nextUnspokenUtterance = tokenizer.nextToken();
If you're asking whether there's a direct way, there isn't. But this way will get rid of all the tokens you don't need and let you carry on.

TextToSpeech:service isn't started?

Hey i a creating app which is TextToSpeech functionality. I write code and run but no any
speech is generate. some error display in logcat. here is logcat
04-11 20:21:30.099: VERBOSE/TtsService(481): TtsService.setLanguage(eng, USA, )
04-11 20:21:30.109: INFO/TextToSpeech.java - speak(849): speak text of length 41
04-11 20:21:30.109: ERROR/TextToSpeech.java - speak(849): service isn't started
I don't understand how to solve this...here is my full code.
public class ExamAppearingActivity extends Activity implements OnInitListener
{
private int MY_DATA_CHECK_CODE = 0;
private TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.examquestionscreen);
if (isVoiceEnabled==1)
{
tts = new TextToSpeech(this, this);
final List<ObjectiveWiseQuestion> QuestionWiseProfile1= db.getOneQuestion(examId);
for (final ObjectiveWiseQuestion cn : QuestionWiseProfile1)
{
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
db=new MySQLiteHelper(getBaseContext());
db.getWritableDatabase();
counter=cn.getCounter();
String question="Question is "+cn.getQuestion();
String option1="Option A is "+cn.getOptionA();
String option2="Option B is "+cn.getOptionB();
String option3="Option C is "+cn.getOptionC();
String option4="Option D is "+cn.getOptionD();
tts.speak(question, TextToSpeech.QUEUE_ADD, null);
tts.speak(option1, TextToSpeech.QUEUE_ADD, null);
tts.speak(option2, TextToSpeech.QUEUE_ADD, null);
tts.speak(option3, TextToSpeech.QUEUE_ADD, null);
tts.speak(option4, TextToSpeech.QUEUE_ADD, null);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
//tts.isLanguageAvailable(Locale.INDIA_HINDI);
startActivity(installIntent);
}
}
}
#Override
public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
// tts.setLanguage(Locale.US);
Locale loc = new Locale ("hi_IN");
tts.setLanguage(loc);
Toast.makeText(ExamAppearingActivity.this,"Text-To-Speech engine is initialized", Toast.LENGTH_LONG).show();
}
else if (status == TextToSpeech.ERROR)
{
Toast.makeText(ExamAppearingActivity.this, "Error occurred while initializing Text-To-Speech engine", Toast.LENGTH_LONG).show();
}
}
This code is run only when i add it on button click but i need to start it from
onCreate() method.
Any help is appreciated.
You can't use tts until onInit has been called.
At the moment, you create it and try to use it within the onCreate method, but it won't have finished being initialised by then.
You're also creating tts twice. The one in onActivityResult makes most sense because you're checking it exists first. I'd get rid of the creation in onCreate, and put all of the actual speaking into onInit.

Categories

Resources