Home > Software engineering >  textToSpeech - unresolved reference in Kotlin
textToSpeech - unresolved reference in Kotlin

Time:08-04

I have been trying to implement textToSpeech on a microphone that you can press on, but the textToSpeech turns red and "unresolved reference" is displayed.

Here is the code from the Main Activity:

vh.miketv.setOnClickListener {
                val text: String =
                    celldata!![position].getText_eng().toString()   "   "   celldata[position].getText_spn()
                textToSpeech.speak(text, QUEUE_FLUSH, null)
            }
            return view

Also, here is everything that I have imported:

import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.speech.tts.TextToSpeech
import android.speech.tts.TextToSpeech.*
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.GridView
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import main.com.cellappkotlin.model.CellDataBean
import java.util.*

I have also tried in Java, and it worked with the following code, but I can't figure it out how to make it work in Kotlin as well:

public void onClick(View view) {
                   String text = celldata.get(i).getText_eng() "   " celldata.get(i).getText_spn();
                   textToSpeech.speak(text,TextToSpeech.QUEUE_FLUSH,null);
               }

The text to speech works generally in this app, I have implemented it somewhere else and everything was okay, but only in this particular case, when I want to press on that microphone, it doesn't seem to work.

Could someone help me understand what is wrong, please? Thank you very much.

CodePudding user response:

Step 1: Extend your activity with TextToSpeech.OnInitListener.

class MainActivity : AppCompatActivity(),TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null

Step 2: Set Language

override fun onInit(status: Int) {
    if (status == TextToSpeech.SUCCESS) {
        val result = tts!!.setLanguage(Locale.US)

        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS","The Language not supported!")
        } else {
           //Do something such as enable the button
        }
    }
}

Step 3: Initialise TextToSpeech class variable in onCreate.

tts = TextToSpeech(this, this)

Step 4: speak the text when you click it.

vh.miketv.setOnClickListener {
            val text: String = "Hello"
            tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null,"")
        }
        return view

Step 5: Stop TextToSpeech Engine when your activity is destroyed.

public override fun onDestroy() {
  // Shutdown TTS
  if (tts != null) {
    tts!!.stop()
    tts!!.shutdown()
  }
  super.onDestroy()
}
  • Related