Android Programming

TTS (Text To Speech) in Fragments

여우래비 2015. 6. 9. 14:23
반응형





I want to implement TTS function in fragment in my app, but failed due to not enough understanding between Activity and Fragment.


But found some sources in stackoverflow.com! (Link:http://stackoverflow.com/questions/16866173/text-to-speech-in-fragment)


However, I failed over and over again.. and found the cause..  It was "return view" code in onInit.


Anyhow, finally I succeeded, below is my source. 


Fragment.java

public class Q01Fragment extends Fragment implements View.OnClickListener, TextToSpeech.OnInitListener {


    private TextToSpeech txts;

    private static final String TAG = "TextToSpeechDemo";

    private static final int MY_DATA_CHECK_CODE = 1234;

    private TextToSpeech tts;

    //private Button btnSpeak;

    //private EditText txtText;


    public static Q01Fragment newInstance() {

        Q01Fragment fragment = new Q01Fragment();

        return fragment;

    }


    public Q01Fragment() {

        // Required empty public constructor

    }


    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,

                             Bundle savedInstanceState) {


        View view = inflater.inflate(R.layout.fragment_q01, container, false);


        Button button = (Button) view.findViewById(R.id.button_Q01);

        button.setOnClickListener(this);


        txts = new TextToSpeech(getActivity(), this);


        // Fire off an intent to check if a TTS engine is installed

        Intent checkIntent = new Intent();

        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);

        startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);


        return view;

    }



    @Override

    public void onDestroy() {

        // Don't forget to shutdown!

        if (txts != null) {

            txts.stop();

            txts.shutdown();

        }

        super.onDestroy();

    }


    private void speakOut() {


        String text = "This is New code";


        txts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

    }

    

    @Override

    public void onClick(View v) {


        switch (v.getId()) {


            case R.id.button_Q01:

                //Toast.makeText(getActivity(), "One Fragment", Toast.LENGTH_SHORT).show();

                speakOut();

                break;

        }

    }


    @Override

    public void onInit(int status) {

        if (status == TextToSpeech.SUCCESS) {

            int result = txts.setLanguage(Locale.US);

            if (result == TextToSpeech.LANG_MISSING_DATA

                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {

                Log.e("TTS", "Language is not supported");

            } else {


            }


        } else {

            Log.e("TTS", "Initilization Failed");

        }

    }



반응형