TTS is very interesting because it can add some nice features to an app. Text to Speech is a feature of Android platform that can be used to "read" the words and make the app talking, or more in detail to synthesize text. 



Text To Speech Engine

The first thing we have to do to use the TTS in our app is initialise the engine. The class that controls the engine is called TextToSpeech,

?
1
engine = new TextToSpeech(this, this);

where the first parameter is the Context and the other one is the listener. The listener is used to inform our app that the engine is ready to be used. In order to be notified we have to implement TextToSpeech.OnInitListener, so we have:
?
1
2
3
4
5
6
7
8
9
10
11
12
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
    ....
    @Override
    public void onInit(int status) {
        Log.d(&Speech&, &OnInit - Status [&+status+&]&);
 
        if (status == TextToSpeech.SUCCESS) {
            Log.d(&Speech&, &Success!&);
            engine.setLanguage(Locale.UK);
        }
    }
}
We use the onInit as callback method, and when the engine is ready, we set the default language that the engine used to read our sentence. 

Read The Words

Now our engine is ready to be used, we need simply pass the string we want to read. To this purpose, we use an EditText so that the user can edit his string and when he clicks on the microphone the app start reading. Without detailing too much the code because is trivial we focus our attention when user clicks on the microphone button:
?
1
2
3
4
5
6
speechButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speech();
            }
        });
where 
?
1
2
3
private void speech() {
    engine.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null, null);
}

we simply have to call the speak method to make our app reading the text! 

Control Text To Speech Engine Parameters

We can have more control on how the engine read the sentence. We can modify for example the pitch and the speech rate.

In the app, for example we used two seek bars to control the pitch and rate. If we want to set the voice pitch we can use setPitch passing a float value.

On the other hand, if we want to change the speech rate we can use setSpeechRate.
In our app, we read this value from two seek bars and the speech method become:
?
1
2
3
4
5
6
   private void speech() {
        engine.setPitch((float) pitch);
        engine.setSpeechRate((float) speed);
        engine.speak(editText.getText().toString(), TextToSpeech.QUEUE_FLUSH, null, null);
    }