Open In App

How to Convert Text to Speech in Android using Kotlin?

Last Updated : 07 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Text to Speech App converts the text written on the screen to speech like you have written “Hello World” on the screen and when you press the button it will speak “Hello World”. Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading on-screen text, but it’s also convenient for those who want to be read too. This feature has come out to be a very common and useful feature for users. We will use Kotlin language for this project. In this article, we will see how to use speak() method of android.speech.tts.TextToSpeech class. And using the same we will convert a text to speech (audio).

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to Create a new project in android studio in kotlin.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/gfg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GeeksforGeeks"
        android:textColor="#189C1E"
        android:textSize="22sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.134" />
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">
        
        <EditText
            android:id="@+id/et_input"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10" >
        </EditText>
  
        <Button
            android:id="@+id/btn_speak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/speak" />
    </LinearLayout>
  
</androidx.constraintlayout.widget.ConstraintLayout>


Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.ayush.myapplication
  
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import android.widget.Button
import android.widget.EditText
import java.util.*
  
// Extending MainActivity TextToSpeech.OnInitListener class
class MainActivity : AppCompatActivity(),TextToSpeech.OnInitListener {
    private var tts: TextToSpeech? = null
    private var btnSpeak: Button? = null
    private var etSpeak: EditText? = null
      
    override fun onCreate(savedInstanceState: Bundle?) {
  
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // view binding button and edit text
        btnSpeak = findViewById(R.id.btn_speak)
        etSpeak = findViewById(R.id.et_input)
         
        btnSpeak!!.isEnabled = false
        
        // TextToSpeech(Context: this, OnInitListener: this)
        tts = TextToSpeech(this, this
  
        btnSpeak!!.setOnClickListener { speakOut() }
  
        }
  
    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 {
                btnSpeak!!.isEnabled = true
            }
        }
    }
    private fun speakOut() {
        val text = etSpeak!!.text.toString()
        tts!!.speak(text, TextToSpeech.QUEUE_FLUSH, null,"")
    }
  
    public override fun onDestroy() {
        // Shutdown TTS when 
        // activity is destroyed
        if (tts != null) {
            tts!!.stop()
            tts!!.shutdown()
        }
        super.onDestroy()
    }
  
}


Note: We need to stop and shut down TextToSpeech Engine when activity is destroyed.

So, our app is ready. And we can see the output.

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads