/**
* Creates the single SpeechRecognizer instance and assigns a listener
* @see CustomRecognitionListener.java
* @param ctx context of the interaction
* */
public void createRecognizer(Context ctx) {
this.ctx = ctx;
PackageManager packManager = ctx.getPackageManager();
List<ResolveInfo> intActivities = packManager.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (intActivities.size() != 0) {
myASR = SpeechRecognizer.createSpeechRecognizer(ctx);
myASR.setRecognitionListener(this);
} else {
myASR = null;
}
}
/**
* Starts speech recognition
* @param languageModel Type of language model used (see Chapter 3 in the book for further details)
* @param maxResults Maximum number of recognition results
*/
public void listen(String languageModel, int maxResults) throws Exception{
if( (languageModel.equals(RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) ||
languageModel.equals(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH)) && (maxResults>=0)) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, ctx.getPackageName());
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, languageModel);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults);
myASR.startListening(intent);
} else {
throw new Exception("Invalid params to listen method");
}
}
public void onResults(Bundle results) {
processAsrResults(results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION),
results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES));
}