Android: How to build Text to Speech Android App with a few lines of code (2019)

Please visit our site: http://www.ikh4ever.com/. For more videos please subscribe our Youtube Channel here: iKh4ever Studio




MainActivity.kt

    lateinit var vTTS:TextToSpeech

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        vTTS = TextToSpeech(applicationContext, OnInitListener { status ->
            //if no error then set language
            vTTS.language = Locale.US
        })

        btnSpeak.setOnClickListener {
            val textToSpeak = textEditForSpeak.text.toString()
            if (textToSpeak == ""){
                Toast.makeText(this,"Please Input Text....", Toast.LENGTH_SHORT).show()
            }else{
                Toast.makeText(this,textToSpeak,Toast.LENGTH_SHORT).show()
                vTTS.speak(textToSpeak,TextToSpeech.QUEUE_FLUSH,null)
            }
        }

        btnStopSpeak.setOnClickListener {
            if (vTTS.isSpeaking){
                vTTS.stop()
            }else{
                Toast.makeText(this, "Not Speaking", Toast.LENGTH_SHORT).show()
            }
        }

    }

    override fun onPause() {
        super.onPause()
        if (vTTS.isSpeaking){
            vTTS.stop()
        }
    }


main_activity.xml


    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <EditText android:layout_width="match_parent" android:layout_height="wrap_content"
                android:padding="12dp"
              android:minHeight="150dp"
              android:hint="Input Text to speak !!!"
              android:textColor="@color/colorAccent"
              android:gravity="start"
              android:id="@+id/textEditForSpeak"
    />

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:padding="1dp"
            android:text="Speak"
            style="@style/TextAppearance.AppCompat"
            android:id="@+id/btnSpeak"
            android:layout_below="@+id/textEditForSpeak"
    />


    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="Stop"
            android:id="@+id/btnStopSpeak"
            android:layout_below="@+id/textEditForSpeak"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"

    />
</RelativeLayout>




Download Full Source Code:


Post a Comment

Previous Post Next Post