Saturday, February 9, 2013

Text-To-Speech

This one is also known as TTS and it is present on Android platform since version 1.6. Usage is uncomplicated but initialization is complicated. Whole initialization issue is about can we have desired Language, is it supported on particular phone. To request language we need to implement OnInitListener interface and that one is defined in android.speech.tts.TextToSpeech.OnInitListener, android.speech.tts.TextToSpeech we need to use TTS and we will import both of them. Before setting any language we want to check what is available and that goes in form question and answer. Inside onCreate we will use Intent:

Intent checkTTSIntent = new Intent();
checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);


Naturally to hear reply we will implement onActivityResult:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MY_DATA_CHECK_CODE) {
        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
            myTTS = new TextToSpeech(this, this);
        } else {
            Intent installTTSIntent = new Intent();
            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
            startActivity(installTTSIntent);
        }
    }
}


Where myTTS is class level variable. If we have TTS data we create TTS instance, otherwise we start installation process which takes user online. Previous two steps are Intent story which is simplest form of IPC on Android platform, everybody should know that. Since we passed as parameter to TTS constructor this as OnInitListener, we should now implement that listener and set language.

public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        if(myTTS.isLanguageAvailable(Locale.ITALY)==TextToSpeech.LANG_COUNTRY_AVAILABLE)
            myTTS.setLanguage(Locale.ITALY);
        else
            myTTS.setLanguage(Locale.UK);
    } else {
        Toast.makeText(this, "TTS failed!", Toast.LENGTH_LONG);
    }
}


If init was success we check can we have Italian, if Italian is not available we settle for proper English. Now that initialization is done, we can pass strings containing desired speech to TTS and listen:

String story1 = "are you done yet";
String story2 = "when it will be ready";
myTTS.speak(story1, TextToSpeech.QUEUE_FLUSH, null);
myTTS.speak(story2, TextToSpeech.QUEUE_ADD, null);


Obviously we are mimicking project manager. If Italian succeeded, we should use “stai ancora finito” and “quando sarĂ  pronto”, according to Google Translate, but that is not important right now.

No comments:

Post a Comment