Header Ads

Using the official TextToSpeech in Android 1.6 tutorial

Update There is a official post from android team on this on http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html

Android 1.6 SDK had been released and previously if you want TTS on your app, you have to use the one from eyes-free, while this one was the whole inspiration of having TTS by default on android, an official API is official. lol

If you have used the one from eyes-free, its mostly the same way except you'll be using android.speech.tts.TextToSpeech

Main
public class Main extends Activity implements TextToSpeech.OnInitListener {
  TextToSpeech tts;
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    tts = new TextToSpeech(this,this);
  }

  public void onInit(int status) {
    Locale loc = new Locale("es", "","");
    if(tts.isLanguageAvailable(loc) >= TextToSpeech.LANG_AVAILABLE){
      tts.setLanguage(loc);
    }
    tts.speak("hola mundo", TextToSpeech.QUEUE_FLUSH, null);
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    tts.shutdown();
  }
}


Explanation
We implement the OnInitListener for us know that the TextToSpeech is ready
public class Main extends Activity implements TextToSpeech.OnInitListener

Create a TextToSpeech instance where the first param is the context and second is the init function (the one we implemented)
tts = new TextToSpeech(this,this);

Function that we implemented, this function will be called after the TextToSpeech is ready to be used
public void onInit(int status) {

Determine if the language is available for us to use ( > TextToSpeech.LANG_AVAILABLE coz higher value means the language is available, use LANG_COUNTRY_AVAILABLE if you want to use UK english or Portuguese spanish)
if(tts.isLanguageAvailable(loc) >= TextToSpeech.LANG_AVAILABLE){

Set new language if the language data is present
tts.setLanguage(loc);

Speak the words, and TextToSpeech.QUEUE_FLUSH means speak it right away.
tts.speak("hola mundo", TextToSpeech.QUEUE_FLUSH, null);

Hope this helps

References
TextToSpeech
TextToSpeech GIT snapshot
Eyes free

Update History
   Jan 17, 2012 - Visual Update

No comments:

Powered by Blogger.