How to create speech to text application in android studio || Google speech Recognization API
To create a speech-to-text application in Android Studio using the Google Speech Recognition API, you can follow these steps:
- Create a new Android Studio project and add the following dependency to the build.gradle file:
pythonimplementation 'com.google.android.gms:play-services-speech:16.0.0'
In the app's main layout file (activity_main.xml), add a Button and a TextView.
In the MainActivity class, create a private variable to hold the SpeechRecognizer object:
javaprivate var speechRecognizer: SpeechRecognizer? = null
- In the onCreate() method, set the Button's onClickListener:
scssfindViewById<Button>(R.id.button).setOnClickListener {
startListening()
}
- Create a private startListening() method that will start the speech recognition process:
kotlinprivate fun startListening() {
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
val speechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
speechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
speechRecognizer?.startListening(speechRecognizerIntent)
}
This method creates a new SpeechRecognizer object, creates an intent for speech recognition, sets the language model to free form, and sets the language to the device's default. It then starts the speech recognition process.
- Override the onResults() method to get the results of the speech recognition process:
kotlinoverride fun onResults(results: Bundle) {
val matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)
findViewById<TextView>(R.id.textView).text = matches?.get(0)
}
This method retrieves the results of the speech recognition process, which are returned as a list of strings. It then updates the TextView with the first string in the list.
- Override the onError() method to handle any errors that may occur during the speech recognition process:
kotlinoverride fun onError(error: Int) {
if (error == SpeechRecognizer.ERROR_NO_MATCH || error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT) {
findViewById<TextView>(R.id.textView).text = "No speech recognized"
}
}
This method checks for two common errors that may occur during the speech recognition process. If either of these errors occur, it updates the TextView to indicate that no speech was recognized.
- In the onDestroy() method, release the speechRecognizer object:
kotlinoverride fun onDestroy() {
super.onDestroy()
speechRecognizer?.destroy()
}
This ensures that the speechRecognizer object is released when the app is closed.
That's it! You have successfully created a speech-to-text application in Android Studio using the Google Speech Recognition API. When the user presses the Button, the app will start listening for speech and update the TextView with the recognized text.
No comments