Text To Speech without textfield and button in Android Studio

五迷三道 提交于 2021-01-29 05:31:10

问题


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 or any button. How can I do that? Need your help.


回答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;

public class MainActivity extends Activity {

    TextToSpeech t1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status != TextToSpeech.ERROR) {
                    t1.setLanguage(Locale.ENGLISH);
                }
            }
        });


        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                t1.speak("welcome to my app", TextToSpeech.QUEUE_FLUSH, null);
            }
        }, 100);


    }

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

}

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




回答2:


Just add this in your onCreate():

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


来源:https://stackoverflow.com/questions/52133256/text-to-speech-without-textfield-and-button-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!