When a notification comes, it outputs it as a voice through TTS, and when the voice output ends, it implements a function that receives a voice input from the user and sends it as a message. So, I wrote the code to perform STT in the onDone function for the TTS object as follows and confirmed that the startSTT() function was executed.
class NotificationListener : NotificationListenerService() {
private fun startSTT() {
val speechRecognizerIntent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, packageName)
putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault())
}
var speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this)
speechRecognizer.setRecognitionListener(recognitionListener())
speechRecognizer.startListening(speechRecognizerIntent)
}
private fun initTextToSpeech() {
tts = TextToSpeech(this) {
if (it == TextToSpeech.SUCCESS) {
val result = tts?.setLanguage(Locale.KOREA)
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Toast.makeText(this, "language not supported", Toast.LENGTH_SHORT).show()
return@TextToSpeech
}
tts?.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
override fun onDone(utteranceId: String) {
startSTT()
}
override fun onError(utteranceId: String) {}
override fun onStart(utteranceId: String) {}
})
}
}
}
}
However, when executing the startSTT() function, the following error message occurs.
SpeechRecognizer should be used only from the application's main thread
How to modify the code to make SpeechRecognizer run on the main thread