The Android Dev website provides an example of doing speech input using the built-in Google Speech Input Activity. The activity displays a pre-configured pop-up with the mic and passes its results using onActivityResult()
My question:
Is there a way to use the SpeechRecognizer
class directly to do speech input without displaying the canned activity? This would let me build my own Activity for voice input.
Also make sure to request the proper permissions from the user. I got stuck with an error 9 return value: INSUFFICIENT_PERMISSIONS, even though I had the proper RECORD_AUDIO permissions listed in the manifest.
In following the sample code here I was able to get the permissions from the user and then the speech recognizer returned good responses.
E.g. This block I put in my onCreate() for the activity, though it could go somewhere else in the UI flow, prior to calling the SpeechRecognizer methods:
Then provide a callback method in the activity for the permissions request:
One other thing I have to change in preetha's example code above where the resulting text is retrieved in the onResults() method. To get the actual text of the translated speech (rather than the size, as the original code prints) either print the value of the constructed string str or get one of the return values in the ArrayList (data). For instance:
You can use
SpeechRecognizer
, though I am not aware of any sample code for it beyond this previous SO question. However, that is new to API level 8 (Android 2.2), and therefore is not widely usable at the time of this writing.Here is the code using SpeechRecognizer class (sourced from here and here):
Define main.xml with a button and give RECORD_AUDIO permission in manifest