Wednesday, March 26, 2014

How to Use Text to Speech on Android



1. Open the Java file for the class you want to use the Text-To-Speech function in. Add the following import statements at the top of your file:import android.speech.tts.TextToSpeech;import android.speech.tts.TextToSpeech.OnInitListener;import java.util.Locale;These are required for using Text-To-Speech and for setting the locale you wish to target.

2. Alter your Java class to use Text-To-Speech. To use the Text-To-Speech functionality, your class must implement the correct interface. Alter your class declaration as follows:public class SpeechClass extends Activity implements OnInitListenerThis example code is an Android Activity class. You should use whichever class name your code already has; the only change you need to make is adding 'implements OnInitListener' to the class declaration.

3. Create an instance of the 'TextToSpeech' object. This is the main object you will need, so add it as an instance variable near the top of your class declaration, before your 'onCreate' method:private TextToSpeech tts;Inside the 'onCreate' method for your Activity, instantiate the Text-To-Speech object:tts = new TextToSpeech(this, this);Your class now has a usable Text-To-Speech object providing access to the resource functionality.

4. Implement the 'onInit' method. Your Integrated Development Environment (IDE) may have been highlighting the fact that you have not yet implemented the interface specified in the class declaration. To address this, add the following method outline to your class:public void onInit(int arg0) {//text to speech code here}This is the method required to use the Text-To-Speech functionality and will contain the code which sets you up to access it.

5. Call the Text-To-Speech functions within your application. Inside the 'onInit' method, add the following code:tts.setLanguage(Locale.US);You can target any locale you like, but this targets U.S. English. Wherever you want your speech to take place in your class, you can do so using the following syntax:String speechText = 'Hello';tts.speak(speechText, TextToSpeech.QUEUE_FLUSH, null);Save your code and run the application to test it.

No comments:

Post a Comment