android - Text-to-Speech in on View Pager -


  • i have view pager, , few text in every page, have button ,on button press text-to-speech event fire

  • i know how use text-to-speech, when comes viewpager dont know

  • code :

    public class mainactivity extends activity implements texttospeech.oninitlistener {

    private texttospeech tts; private button btnspeak; private edittext txttext;  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main);       tts = new texttospeech(this, this);      btnspeak = (button) findviewbyid(r.id.btnspeak);      txttext = (edittext) findviewbyid(r.id.txttext);      // button on click event     btnspeak.setonclicklistener(new view.onclicklistener() {          @override         public void onclick(view arg0) {             speakout();         }      }); }  @override public void ondestroy() {     // don't forget shutdown!     if (tts != null) {         tts.stop();         tts.shutdown();     }     super.ondestroy(); }  @override public void oninit(int status) {     // todo auto-generated method stub      if (status == texttospeech.success) {          int result = tts.setlanguage(locale.us);          // tts.setpitch(5); // set pitch level          // tts.setspeechrate(2); // set speech speed rate          if (result == texttospeech.lang_missing_data                 || result == texttospeech.lang_not_supported) {             log.e("tts", "language not supported");         } else {             btnspeak.setenabled(true);             speakout();         }      } else {         log.e("tts", "initilization failed");     }  }  private void speakout() {      string text = txttext.gettext().tostring();      tts.speak(text, texttospeech.queue_flush, null); } 

    }

-- how implement in viewpager,and speak(convert) text particular in page

the easiest way make tts object static in mainactivity

then fragments can call mainactivity.tts.stop() etc.

it better include helper methods in mainactivity such as:

public static texttospeech gettts(){ return tts; } 

and avoid null pointers:

public static boolean isttsavailable(){ return tts != null // && ttsinitialised } 

where set static boolean true if oninit returned success.

mainactivity continue handle releasing tts object in ondestroy etc.

as side note, it's practice check out memory profiler in android studio make sure holding static reference object such has no adverse effects. before , after analysis , run garbage collector manually etc check holding no unwanted references after activity has been destroyed. generic advice, whenever making code change such this, it's know there no side-effects.


Comments

Popular posts from this blog

Ansible - ERROR! the field 'hosts' is required but was not set -

customize file_field button ruby on rails -

SoapUI on windows 10 - high DPI/4K scaling issue -