I am using recognition listener for speech recognition in android. The basic construct of my class is as follows:
class SpeechInput implements RecognitionListener {
Intent intent;
SpeechRecognizer sr;
boolean stop;
public void init() {
sr = SpeechRecognizer.createSpeechRecognizer(context);
sr.setRecognitionListener(this);
intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,context.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,3);
}
...
}
I am stuck in a situation where I want to run android recognition listener in a loop, something over the lines of:
for(int i=0; i<N; i++) {
// Some processing code
sr.startListening(intent);
}
Now, I want to wait for the output before it starts listening again. In order to achieve this, I tried to use locking mechanism as follows:
for(int i=0; i<N; i++) {
// Some processing code
sr.startListening(intent);
stop = false;
new Task().execute().get();
}
where Task is an asyncTask defined as follows:
private class Task extends AsyncTask<Void,Void,Void> {
@Override
protected Void doInBackground(Void... params) {
try {
int counter = 0;
while(!stop) {
counter++;
}
} catch(Exception e) {
}
return null;
}
}
The boolean value 'stop' is updated in the 'onResults' method of RecognitionListener as follows:
public void onResults(Bundle results) {
...
stop = true;
}
The problem is that speech recognition is not working at all. Nothing is happening, it is not even starting. I guess this is because the asyncTask is taking up all the processor time. Can you please guide me towards an architecture where I would be able to achieve this? Thank you.
Restart the listening when you receive a result. No loop needed, no waiting needed.
I'm not an expert on Speech recognition on Android but you are probably blocking the Main thread with the call
new Task().execute().get();
So the speech recognition is probably never started.