Skip to content Skip to sidebar Skip to footer

Text To Speech Without Textfield And Button In Android Studio

So, I want to create a text to speech without the use of textfield and button in Android Studio. For example when I open the app it will say 'WELCOME TO MY APP' without text field

Solution 1:

You could do like below:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;

import java.util.Locale;

publicclassMainActivityextendsActivity {

    TextToSpeech t1;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = newTextToSpeech(getApplicationContext(), newTextToSpeech.OnInitListener() {
            @OverridepublicvoidonInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.ENGLISH);
                }
            }
        });


        finalHandlerhandler=newHandler();
        handler.postDelayed(newRunnable() {
            @Overridepublicvoidrun() {
                t1.speak("welcome to my app", TextToSpeech.QUEUE_FLUSH, null);
            }
        }, 100);


    }

    publicvoidonPause() {
        if (t1 != null) {
            t1.stop();
            t1.shutdown();
        }
        super.onPause();
    }

}

codes are self explanatory and I tested it with successful result.

Solution 2:

Just add this in your onCreate():

myTTS = newTextToSpeech(getApplicationContext(), newTextToSpeech.OnInitListener() {
            @OverridepublicvoidonInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    // replace this Locale with whatever you want                    LocalelocaleToUse=newLocale("en","US");
                    myTTS.setLanguage(localeToUse);
                    myTTS.speak("Hi, Welcome to my app!", TextToSpeech.QUEUE_FLUSH, null);
                }
            }
        });

Post a Comment for "Text To Speech Without Textfield And Button In Android Studio"