Text to Speech Conversion



Android SDK bring out a cool feature (from Android 1.6) called Text to Speech (TTS) which speaks the given text in different languages. Now I explore how they manage this to us.

What I do here? How to work with android text to speech or android speech synthesis. Also explained changing the language type, pitch level and speed level.


Step 1: Create a new project by going to File ⇒ New Android Project and fill required details.
Step 2: Create a TextToSpeechActivity which extends Activity & add this activity in manifestfile.  
Step 3: Now add following code to your TextToSpeechActivity class.

 public class TextToSpeechActivity extends Activity {  
   
      private Button speakButton;  
      private EditText txtWriteText;  
      private TextToSpeech tts;  
      private Context context = this;  
   
      @Override  
      protected void onCreate(Bundle savedInstanceState) {  
   
           super.onCreate(savedInstanceState);  
           setContentView(R.layout.activity_text_to_speech);  
   
           speakButton = (Button) findViewById(R.id.speakButton);  
           txtWriteText = (EditText) findViewById(R.id.editTextWritenlisten);  
   
           // initialize the object with listener  
           try {  
                tts = new TextToSpeech(context, new OnInitListener() {  
                     @Override  
                     public void onInit(int status) {  
                          // check initialization on tts & set language  
                          if (status != TextToSpeech.ERROR) {  
                               // can set different language  
                               tts.setLanguage(Locale.US);  
                          }  
                     }  
                });  
                speakButton.setOnClickListener(new OnClickListener() {  
                     @Override  
                     public void onClick(View v) {  
   
                          String text = txtWriteText.getText().toString();  
                          tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);  
                     }  
                });  
           } catch (Exception e) {  
                e.printStackTrace();  
           }  
      }  
        
      @Override  
      protected void onDestroy() {  
           // Don't forget to shutdown tts!  
           if (tts != null) {  
                tts.stop();  
                tts.shutdown();  
           }  
           super.onDestroy();  
      }  
 }  

Step 4: Now you can run the application, put some text in EditText field & click the button to listen. :)  
More: You can also change Language, Pitch Rate & Speed Rate By following methods.  

Change language:


 tts.setLanguage(Locale.GERMAN); // german language  

Change Pitch Rate:
 
 tts.setPitch(.7f);  

Change Speed Rate:
 
 tts.setSpeechRate(2);