简体   繁体   中英

using text to speech in an android class

I am new in java and android. I need to use text to speech in a class not in the activity, is it possible? if yes, how can I do it? I just found good tutorials which it was done in an activity.

Thank you!

I know this is rather late but if your still stumped (hopefully not); or for the purposes of anyone else with the same/similar question.

An stand alone class is pretty simple to do. It needs context and if you want to pass it an message. Pass both in the constructor.

So you end up with something, which looks like this.

    public class MyTTS {

        private Context context;
        private TextToSpeech tts;
        private String txt;
        private String TAG = MyTTS.class.getSimpleName();

        public MyTTS(Context context, String txt) {
            this.context = context;
            this.txt = txt;
            handleSpeech();
        }

        private void handleSpeech() {

            tts = new TextToSpeech(context, new TextToSpeech.OnInitListener() {

                @Override
                public void onInit(int status) {

                    if (status == TextToSpeech.SUCCESS) {
                        int result = tts.setLanguage(Locale.ENGLISH);
                        if (result == TextToSpeech.LANG_MISSING_DATA || result == TextTo

Speech.LANG_NOT_SUPPORTED) {
                        Log.e(TAG, "This Language is not supported");
                    } else {
                        saySomeThing();
                    }
                } else {
                    Log.e(TAG, "Initialization Failed!");
                }
            }
        });
    }

    private void saySomeThing() {

        if((txt != null) && (txt.length() > 0)) {
            tts.speak(txt, TextToSpeech.QUEUE_FLUSH, null);
        }

        else {
            tts.shutdown();
        }
    }

To execute it:

new MyTTS(context, message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM