Make sure you use a single SpeechRecognizer object within the action. A quick and dirty way to make it static.
private static SpeechRecognizer speech = null;
Modify your listen() method to check for null on the speech object.
private void listen() { if (speech == null) { speech = SpeechRecognizer.createSpeechRecognizer(this); speech.setRecognitionListener(this); } intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, "en"); intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, this.getPackageName()); intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH); intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3); speech.startListening(intent); }
Call the listening method in onResults() and in onError() .
public void onResults(Bundle arg0) { // TODO Auto-generated method stub Log.i(TAG, "onresults"); ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); String s = ""; for (String result:matches) s += result + "\n"; vrtext.setText(s); //speech.startListening(intent); listen(); } public void onError(int arg0) { // TODO Auto-generated method stub Log.i(TAG, "error code: " + arg0); listen(); }
And finally, don't forget to do the necessary cleanup in onDestroy() .
@Override public void onDestroy() { super.onDestroy(); speech.destroy(); }
Ξ G I Π AND O Aug 08 '14 at 10:31
source share