I'm new to Kotlin, and essentially I'm trying to create an app that counts how many times someone says a keyword. I'm using the SpeechRecognizer API, and I'm having trouble creating a RecognitionListener.
Below is the problematic code:
private val speech: SpeechRecognizer by lazy { SpeechRecognizer.createSpeechRecognizer(this) }
if (SpeechRecognizer.isRecognitionAvailable(this)) {
Toast.makeText(this, "Voice recognition available.", Toast.LENGTH_SHORT).show()
val speechRecognizer = speech.setRecognitionListener(this)
val recognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH)
putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, applicationContext.packageName)
putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 3)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
putExtra(RecognizerIntent.EXTRA_PREFER_OFFLINE, true)
}
}
speechRecognizer.startListening(recognizerIntent)
The problem comes in the line wherein I create the speechRecognizer:
val speechRecognizer = speech.setRecognitionListener(this)
There's a red squiggly underneath this, saying there is a type mismatch: "Inferred type is MyActivity but RecognitionListener! was expected."
I don't quite understand this... isn't what I'm doing creating a RecognitionListener? Then why does it need a RecognitionListener to be passed into it? I know I've gone horribly wrong somewhere, but I don't know where and I'm lost after searching all over online to find an answer. Any help would be greatly appreciated.
If it's helpful, I've been trying to follow Stephen Vinouze's guide on hot keyword listening found here: https://betterprogramming.pub/implement-continuous-speech-recognition-on-android-1dd2f4b562fd
Anyway, thanks in advance. Let me know if there is anything else I need to provide.
Stephen