Text to Speech – Kotlin Android

To convert Text to Speech in Android, you may use speak() method of android.speech.tts.TextToSpeech class.

In this tutorial – Android Text To Speech, we will learn how to use TextToSpeech class and convert text to speech (audio) with the help of a Kotlin Android Application.

Steps – Text to Speech Conversion

Following are the steps we have to take while using speak() method of TextToSpeech.

Step 1: Extend your activity with TextToSpeech.OnInitListener.

class MainActivity : AppCompatActivity(),TextToSpeech.OnInitListener

Step 2: Initialize TextToSpeech class variable.

tts = TextToSpeech(this, this)

TextToSpeech(Context, OnInitListener)

Step 3: You may set an event, which can trigger the Speech output. A button onClickListener is used in this example.

buttonSpeak!!.setOnClickListener { speakOut() }
private fun speakOut() {
    val text = editText!!.text.toString()
    tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null,"")
}

Step 4: When your application is started, TextToSpeech Engine may take some duration of time for initialization. To avoid speaking out, you may initially disable the button to speak. When the TextToSpeech Engine is initialized, onInit() function is called, which should be overridden and you may enable the button here.

Step 5: And finally, when your Activity is destroyed, stop and shutdown TextToSpeech Engine.

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

Android Text To Speech – Kotlin Example

Following are the details of the Android Application we created for this example.

Application NameTextToSpeechApp
Company nametutorialkart.com
Minimum SDKAPI 21: Android 5.0 (Lollipop)
ActivityEmpty Activity

You may keep rest of the values as default and create Android Application with Kotlin Support.

Following are the MainActivity.kt (class file) and activity_main.xml (layout file).

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.tutorialkart.texttospeechapp.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
        <EditText
            android:id="@+id/edittext_input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" >
            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Speak" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

MainActivity.kt

package com.tutorialkart.texttospeechapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.Button
import android.widget.EditText
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity(),TextToSpeech.OnInitListener {

    private var tts: TextToSpeech? = null
    private var buttonSpeak: Button? = null
    private var editText: EditText? = null

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

        buttonSpeak = this.button_speak
        editText = this.edittext_input

        buttonSpeak!!.isEnabled = false;
        tts = TextToSpeech(this, this)

        buttonSpeak!!.setOnClickListener { speakOut() }
    }

    override fun onInit(status: Int) {

        if (status == TextToSpeech.SUCCESS) {
            // set US English as language for tts
            val result = tts!!.setLanguage(Locale.US)

            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                Log.e("TTS","The Language specified is not supported!")
            } else {
                buttonSpeak!!.isEnabled = true
            }

        } else {
            Log.e("TTS", "Initilization Failed!")
        }

    }

    private fun speakOut() {
        val text = editText!!.text.toString()
        tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null,"")
    }

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

}

Run the application, and you will get the following output in the screen.

Output

Android Text To Speech - Main Activity

Type in some text into the text input.

Android Text To Speech - Kotlin Example

Click on SPEAK button, and you will hear the Speech.

Conclusion

In this Kotlin Android Tutorial, we learned how to use TextToSpeech class to convert text to audio.