Step 1 MAIN.XML
<?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"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:textSize="20dp"
android:textColor="@color/purple_200"
android:gravity="center"
android:text="Text To Speech Program" />
<EditText
android:layout_width="match_parent"
android:hint="Enter Text"
android:id="@+id/text"
android:layout_margin="20dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:text="Convert Text To Speech"
android:layout_margin="20dp"
android:background="@color/purple_500"
android:id="@+id/btn1"
android:textColor="#FFFFFF"
android:onClick="ButtonClick"
android:textSize="15dp"
android:layout_height="wrap_content" />
</LinearLayout>
Step 2 MAIN.JAVA
package in.learncodewithrk.demo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
EditText t1;
private TextToSpeech Speech;
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Speech=new TextToSpeech(this,this);
t1=findViewById(R.id.text);
btn=findViewById(R.id.btn1);
}
@Override
public void onInit(int status) {
if(status==TextToSpeech.SUCCESS){
int result=Speech.setLanguage(Locale.US);
if(result==TextToSpeech.LANG_MISSING_DATA || result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS","Lang not Supported");
btn.setVisibility(View.GONE);
}else{
btn.setVisibility(View.VISIBLE);
}
}
else{
Log.e("TTS","Failed initialztn");
}
}
public void ButtonClick(View view){
String myText=t1.getText().toString();
Speech.speak(myText,TextToSpeech.QUEUE_FLUSH,null);
}
}
0 Comments