0

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

  • 1
    Basically it's saying to run the code on ActivityMain which is the main thread. So I am not sure how you are calling it, but all that code needs to be moved to the ActivityMain then call everything from the main activity – Camp Nerd Nov 24 '22 at 16:38
  • I solved the problem by using looper and handler. – user18560558 Nov 25 '22 at 08:42

0 Answers0