Skip to content

Instantly share code, notes, and snippets.

@efeyc
Created July 27, 2017 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save efeyc/e03708f7d2f7d7b443e08c7fbce52968 to your computer and use it in GitHub Desktop.
Save efeyc/e03708f7d2f7d7b443e08c7fbce52968 to your computer and use it in GitHub Desktop.
...
private void initSpeechRecognizer() {
// Create the speech recognizer and set the listener
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context);
speechRecognizer.setRecognitionListener(recognitionListener);
// Create the intent with ACTION_RECOGNIZE_SPEECH
speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.US);
listen();
}
...
public void listen() {
// startListening should be called on Main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> speechRecognizer.startListening(speechIntent);
mainHandler.post(myRunnable);
}
...
RecognitionListener recognitionListener = new RecognitionListener() {
...
@Override
public void onError(int errorCode) {
// ERROR_NO_MATCH states that we didn't get any valid input from the user
// ERROR_SPEECH_TIMEOUT is invoked after getting many ERROR_NO_MATCH
// In these cases, let's restart listening.
// It is not recommended by Google to listen continuously user input, obviously it drains the battery as well,
// but for now let's ignore this warning
if ((errorCode == SpeechRecognizer.ERROR_NO_MATCH) || (errorCode == SpeechRecognizer.ERROR_SPEECH_TIMEOUT)) {
listen();
}
}
@Override
public void onResults(Bundle bundle) {
// it returns 5 results as default.
ArrayList<String> results = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
// a method that finds the best matched player, and updates the view.
findBestMatchPlayer(results);
}
...
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment