Java Code for An Android App: Text To Speech Converter

 



import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {

    private TextToSpeech tts;
    private Button btnSpeak;
    private EditText txtText;
    private final int REQUEST_WRITE_STORAGE = 112;
    private final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize TextToSpeech
        tts = new TextToSpeech(this, this);

        // Get reference to UI elements
        btnSpeak = findViewById(R.id.btn_speak);
        txtText = findViewById(R.id.txt_text);

        // Request permission to write to external storage
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
            }
        }

        // Set click listener for speak button
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Get input text
                String text = txtText.getText().toString();

                // Check if TextToSpeech is initialized
                if (tts != null) {
                    // Set language to US English
                    tts.setLanguage(Locale.US);

                    // Speak the input text
                    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

                    // Save speech to .mp3 file
                    saveToMp3(text);
                }
            }
        });
    }

    private void saveToMp3(String text) {
        // Check if external storage is available
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // Create directory to store file
            File dir = new File(Environment.getExternalStorageDirectory(), "MySpeech");
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // Create file
            File file = new File(dir, "speech.mp3");

            try {
                // Initialize FileOutputStream
                FileOutputStream fos = new FileOutputStream(file);

                // Generate speech and save to file
                tts.synthesizeToFile(text, null, fos, "speech");

                // Close FileOutputStream
                fos.close();

                // Show success message
                Toast.makeText(this, "Speech saved to " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();
            } catch (FileNotFoundException e) {
                Log.e(TAG, "FileNotFoundException: " + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.getMessage());
                e.printStackTrace();
            }
        } else {
            // External storage is not available, show error message
            Toast.makeText(this, "External storage not available", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            // TextToSpeech initialized successfully
        } else {
            // TextToSpeech initialization failed
            Toast.makeText(this, "TextToSpeech initialization failed", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

       

Comments