Program 7
Program 7
Develop a simple application with one EditText so that the user can
write some text in it. Create a button called “Convert Text to Speech” that
converts the user input text into voice.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textAlignment="center"
tools:context=".MainActivity">
<TextView
android:layout_width="291dp"
android:layout_height="58dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="67dp"
android:layout_marginBottom="617dp"
android:text="Text to Speech"
android:textAlignment="center"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="113dp"
android:layout_marginBottom="484dp"
android:ems="10"
android:inputType="textPersonName"
android:hint="enter text here"
android:text="" />
<Button
android:id="@+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:onClick="convert"
android:layout_marginEnd="185dp"
android:layout_marginBottom="359dp"
android:text="convert" />
</RelativeLayout>
Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
Once you have set the language, you can call speak method of the class to
speak the text. Its syntax is given below −
ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
Apart from the speak method, there are some other methods available in the
TextToSpeech class. They are listed below −
2 getLanguage()
This method returns a Locale instance describing the language.
3 isSpeaking()
This method checks whether the TextToSpeech engine is busy speaking.
4 setPitch(float pitch)
This method sets the speech pitch for the TextToSpeech engine.
5 setSpeechRate(float speechRate)
This method sets the speech rate.
6 shutdown()
This method releases the resources used by the TextToSpeech engine.
7 stop()
This method stop the speak.
JAVA Code
package com.example.lb7;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;