Skip to content

Instantly share code, notes, and snippets.

@abircse
Created March 6, 2021 09:21
Show Gist options
  • Save abircse/7dea060a029ce83885d50365e845d10b to your computer and use it in GitHub Desktop.
Save abircse/7dea060a029ce83885d50365e845d10b to your computer and use it in GitHub Desktop.
Speech to text converter android
/*
* Microphone Item click to record
*/
yourmicrophoneuicon.setOnClickListener {
// Get the Intent action
val sttIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
// Language model defines the purpose, there are special models for other use cases, like search.
sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
// Adding an extra language, you can use any language from the Locale class.
sttIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
// Text that shows up on the Speech input prompt.
sttIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak now!")
try {
// Start the intent for a result, and pass in our request code.
startActivityForResult(sttIntent, 1)
} catch (e: ActivityNotFoundException) {
// Handling error when the service is not available.
e.printStackTrace()
showMessage("Your device does not support Speech to text recognition")
}
}
/*
* Get Result
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
// Handle the result for our request code.
1 -> {
// Safety checks to ensure data is available.
if (resultCode == Activity.RESULT_OK && data != null) {
// Retrieve the result array.
val result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
// Ensure result array is not null or empty to avoid errors.
if (!result.isNullOrEmpty()) {
// Recognized text is in the first position.
val recognizedText = result[0]
/*
you can get your voice to text result in
recognizedText Object & use it where you need
*/
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment