/*
========================================================================================
Filename: 29_TextToSpeechApp.txt
Program 29: Create an app to convert text to speech.
Files Included: MainActivity.java
========================================================================================

WHAT ALL TO DO / SETUP INSTRUCTIONS:
----------------------------------------------------------------------------------------
1. UI Components to Add (in res/layout/activity_main.xml):
   Add 1 TextView: 'Text to Speech'
   Add 1 EditText (TextBox):
     - textInput (Hint: 'Enter text')
   Add 1 Button:
     - Text: 'Speak', onClick: 'speakText'

2. Layout Configuration:
   - LinearLayout (vertical, gravity='center', padding 20dp)

3. Menu Configuration:
   - None required.

4. Themes Configuration (res/values/themes.xml):
   - Theme.MaterialComponents.DayNight.NoActionBar in themes.xml.

5. AndroidManifest.xml:
   <activity android:name=".MainActivity" android:exported="true" />

6. Additional Files & Resources Required:
   - Implements TextToSpeech.OnInitListener. Remember to shut down TextToSpeech in onDestroy().
========================================================================================
*/

// ======================================================================================
// File: MainActivity.java
// ======================================================================================
package com.example.texttospeechapp;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
    EditText textInput;
    TextToSpeech textToSpeech;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textInput = findViewById(R.id.textInput);
        textToSpeech = new TextToSpeech(this, status -> {
            if (status == TextToSpeech.SUCCESS) {
                textToSpeech.setLanguage(Locale.US);
            }
        });
    }
    public void speakText(View view) {
        String text = textInput.getText().toString();
        if (text.isEmpty()) {
            Toast.makeText(this, "Enter some text", Toast.LENGTH_SHORT).show();
        } else {
            textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);
        }
    }
    @Override
    protected void onDestroy() {
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
        super.onDestroy();
    }
}
