Cdacians

Cdacians
Cdacians

Friday 14 September 2012

Android text to speech example



Android text to speech example
Welcome back readers!! Before I start with the post, would like to say thanks for your constant feedback and appreciations which I am getting in mails.
In this post, we are going to develop a simple application which reads out the text you typed. Sounds nice??. Follow the post to create one for you. :)
Package ‘android.speech.tts’:
Android SDK provides built-in package called ‘android.speech.tts’ to handle text to speech capabilities. It synthesizes speech from text for immediate playback or to create a sound file.
Let us start with the application development:
Before we start with developing application, download code from here to follow with the below listings.
  • Layout creation:Create new android project [File >> New >> Android Project] with project name TexttoSpeech
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish
Create a simple layout with one text box to get text from User and one button to trigger ‘Speak’ method to read out the text you typed.
Application layout – main.xml:
Open main.xml under /res/layout and add replace it with the below XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:ignore="HardcodedText" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="15dip"
        android:text="Text To Speech"
        android:textColor="#0587d9"
        android:textSize="26dip"
        android:textStyle="bold" />
 
    <EditText
        android:id="@+id/txtText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:layout_marginTop="20dip"
        android:hint="Enter text to speak" />
 
    <Button
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dip"
        android:enabled="false"
        android:text="Speak" />
 
</LinearLayout>
Application layout will look like:
Change to graphical layout of main.xml, the layout design should look like below:
We are done with application layout. Now we will implement the logic in TextoSpeechActivity class, just open it and proceed with the below listings:
Implement onInitListener interface in your TexttoSpeechActivity class as shown below:
1
public class TexttoSpeechActivity extends Activity implements OnInitListener
Create following objects under TextoSpeechActivity class:
1
2
3
4
//create TextToSpeech native object
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
Update onCreate method with below snippet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                //Set application layout
        setContentView(R.layout.main);
                //Initialize the tts object
        tts = new TextToSpeech(this, this);
                //Refer 'Speak' button
        btnSpeak = (Button) findViewById(R.id.btnSpeak);
                //Refer 'Text' control
        txtText = (EditText) findViewById(R.id.txtText);
        //Handle onClick event for button 'Speak'
        btnSpeak.setOnClickListener(new View.OnClickListener() {
 
            public void onClick(View arg0) {
                                //Method yet to be defined
                 speakOut();
            }
 
        });
    }
Include onInit method which signals the completion of the TextToSpeech engine initialization. Your device will take some small fraction of time to initialize TTS engine, so we are calling onInit method to make sure that whether it is initialized properly or not. Include the below code snipper following the onCreate method:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void onInit(int status) {
        // TODO Auto-generated method stub
          //TTS is successfully initialized
        if (status == TextToSpeech.SUCCESS) {
                       //Setting speech language
            int result = tts.setLanguage(Locale.US);
           //If your device doesn't support language you set above
            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                           //Cook simple toast message with message
                Toast.makeText(this, "Language not supported", Toast.LENGTH_LONG).show();
                Log.e("TTS", "Language is not supported");
            }
                 //Enable the button - It was disabled in main.xml (Go back and Check it)
                        else {
                btnSpeak.setEnabled(true);
            }
            //TTS is not initialized properly
        } else {
                    Toast.makeText(this, "TTS Initilization Failed", Toast.LENGTH_LONG).show();
            Log.e("TTS", "Initilization Failed");
        }
    }
Create ‘Speak’ method which handles speech activity:
1
2
3
4
5
6
7
8
9
10
11
12
private void speakOut() {
         //Get the text typed
        String text = txtText.getText().toString();
         //If no text is typed, tts will read out 'You haven't typed text'
         //else it reads out the text you typed
        if (text.length() == 0) {
            tts.speak("You haven't typed text", TextToSpeech.QUEUE_FLUSH, null);
        } else {
            tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
        }
 
    }
TextToSpeech object – tts service should be shut down when the application is about to be closed, add onDestroy method:
1
2
3
4
5
6
7
8
public void onDestroy() {
        // Don't forget to shutdown!
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }
        super.onDestroy();
    }
Demo:
Let us test the application:
Run click on the project >> Run as >> Android application >> Choose emulator or device
You could see this screen:
Try clicking ‘Speak’ button with and without providing text.


Thanks
akm
www.cdacians.com

No comments:

Post a Comment