Use Text to Speech in Android

Use Text to Speech in Android

Text to Speech (TTS) is an assistive technology that is used to convert a text to synthesized speech. Text to Speech is a built-in feature in the Android platform.

In the layout XML file, we added EditText and Button elements. The user will be able to type text into the field, then the button was pressed it will hear spoken.

app/src/main/res/layout/activity_main.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/myEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />

    <Button
        android:id="@+id/myButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myEditText"
        android:layout_centerHorizontal="true"
        android:text="Speak" />

</RelativeLayout>

We initialize the TextToSpeech. If initialization was successful, then we set a US English locale for the speech operations. By using speak() method, we convert a text to the synthesized speech.

app/src/main/java/com/example/app/MainActivity.kt

package com.example.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*

class MainActivity : AppCompatActivity()
{
    private lateinit var tts: TextToSpeech

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

        tts = TextToSpeech(this, TextToSpeech.OnInitListener { status ->
            if (status == TextToSpeech.SUCCESS) {
                tts.language = Locale.US
            } else {
                Log.d("MY_APP", "Initilization failed")
            }
        })

        myButton.setOnClickListener {
            tts.speak(myEditText.text, TextToSpeech.QUEUE_FLUSH, null, null)
        }
    }
}
Use Text to Speech in Android

Leave a Comment

Cancel reply

Your email address will not be published.