Internet Permission of Android Manifest are need to be added
<uses-permission android:name="android.permission.INTERNET"/>
Below is the complete code for the activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:layout_margin="30dp"
tools:context=".MainActivity">
<!--To add text in the app-->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:layout_marginBottom="20dp"
android:hint="Enter Any Sentence"
android:gravity="center"
android:textSize="16dp"/>
<!--when you press this button it will
convert text into speech-->
<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_gravity="center"/>
<!--To display the name of GeeksForGeeks -->
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="70dp"
android:gravity="center_horizontal"
android:text="GEEKSFORGEEKS"
android:textColor="@android:color/holo_green_dark"
android:textSize="36sp" />
</LinearLayout>
Below is the complete code for the MainActivity.java file.
package com.gfg.android_convert_text_speech;
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;
public class MainActivity extends AppCompatActivity {
EditText Text;
Button btnText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);
// create an object textToSpeech and adding features into it
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
@Override
public void onInit(int i) {
// if No error is found then only it will run
if(i!=TextToSpeech.ERROR){
// To Choose language of speech
textToSpeech.setLanguage(Locale.UK);
}
}
});
// Adding OnClickListener
btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);
}
});
}
}
The user may choose another language as well. For that refer to the below image to see how to do that.