Skip to main content

Android TextToSpeech Tutorial

In android, you can convert your text into speech by the help of TextToSpeech class. After completion of the conversion, you can playback or create the sound file.

Constructor of TextToSpeech class

  • TextToSpeech(Context context, TextToSpeech.OnInitListener)

Methods of TextToSpeech class

The commonly used methods of TextToSpeech class are as follows:
MethodDescription
int speak (String text, int queueMode, HashMapparams)converts the text into speech. Queue Mode may be QUEUE_ADD or QUEUE_FLUSH. Request parameters can be null, KEY_PARAM_STREAM, KEY_PARAM_VALUME etc.
int setSpeechRate(float speed)it sets the speed for the speech.
int setPitch(float speed)it sets the pitch for the speech.
int setLanguage (Locale loc)it sets the locale specific language for the speech.
void shutdown()it releases the resource set by TextToSpeech Engine.
int stop()it interrupts the current utterance (whether played or rendered to file) and discards other utterances in the queue.

TextToSpeech.OnInitListener Interface

You need to implement TextToSpeech.OnInitListener interface, for performing event handling on TextToSpeech engine.

Method of TextToSpeech.OnInitListener Interface

There is only one method in this interface.
MethodDescription
void onInit (int status)Called to signal the completion of the TextToSpeech engine initialization. The status can be SUCCESS or ERROR.

Android TextToSpeech Example

Let's write the code to convert text into voice.

activity_main.xml

Drag one textview, one edittext and one button for the layout. Now the activity_main.xml file will look like this:
File: activity_main.xml
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <EditText  
  8.         android:id="@+id/editText1"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_marginLeft="77dp"  
  14.         android:layout_marginTop="42dp"  
  15.         android:ems="10" >  
  16.   
  17.         <requestFocus />  
  18.     </EditText>  
  19.   
  20.     <Button  
  21.         android:id="@+id/button1"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_alignLeft="@+id/editText1"  
  25.         android:layout_below="@+id/editText1"  
  26.         android:layout_marginLeft="59dp"  
  27.         android:layout_marginTop="39dp"  
  28.         android:text="Speak" />  
  29.   
  30.     <TextView  
  31.         android:id="@+id/textView1"  
  32.         android:layout_width="wrap_content"  
  33.         android:layout_height="wrap_content"  
  34.         android:layout_alignBaseline="@+id/editText1"  
  35.         android:layout_alignBottom="@+id/editText1"  
  36.         android:layout_alignParentLeft="true"  
  37.         android:text="Enter Text:" />  
  38.   
  39. </RelativeLayout>  

Activity class

Let's see the code to speak the given text.
File: MainActivity.java
  1. package com.example.texttospeech;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. import java.util.Locale;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.speech.tts.TextToSpeech;  
  11. import android.util.Log;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.EditText;  
  15. public class MainActivity extends Activity implements  
  16. TextToSpeech.OnInitListener {  
  17. /** Called when the activity is first created. */  
  18.   
  19. private TextToSpeech tts;  
  20. private Button buttonSpeak;  
  21. private EditText editText;  
  22.   
  23. @Override  
  24. public void onCreate(Bundle savedInstanceState) {  
  25. super.onCreate(savedInstanceState);  
  26. setContentView(R.layout.activity_main);  
  27.   
  28. tts = new TextToSpeech(thisthis);  
  29. buttonSpeak = (Button) findViewById(R.id.button1);  
  30. editText = (EditText) findViewById(R.id.editText1);  
  31.   
  32. buttonSpeak.setOnClickListener(new View.OnClickListener() {  
  33.     @Override  
  34.     public void onClick(View arg0) {  
  35.         speakOut();  
  36.     }  
  37.   
  38. });  
  39. }  
  40.   
  41. @Override  
  42. public void onDestroy() {  
  43. // Don't forget to shutdown tts!  
  44. if (tts != null) {  
  45.     tts.stop();  
  46.     tts.shutdown();  
  47. }  
  48. super.onDestroy();  
  49. }  
  50.   
  51. @Override  
  52. public void onInit(int status) {  
  53.   
  54. if (status == TextToSpeech.SUCCESS) {  
  55.   
  56.     int result = tts.setLanguage(Locale.US);  
  57.   
  58.     if (result == TextToSpeech.LANG_MISSING_DATA  
  59.             || result == TextToSpeech.LANG_NOT_SUPPORTED) {  
  60.         Log.e("TTS""This Language is not supported");  
  61.     } else {  
  62.         buttonSpeak.setEnabled(true);  
  63.         speakOut();  
  64.     }  
  65.   
  66. else {  
  67.     Log.e("TTS""Initilization Failed!");  
  68. }  
  69.   
  70. }  
  71.   
  72. private void speakOut() {  
  73. String text = editText.getText().toString();  
  74. tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);  
  75. }  
  76.   
  77.     @Override  
  78.     public boolean onCreateOptionsMenu(Menu menu) {  
  79.         // Inflate the menu; this adds items to the action bar if it is present.  
  80.         getMenuInflater().inflate(R.menu.activity_main, menu);  
  81.         return true;  
  82.     }  
  83.   
  84. }  

Comments

Popular posts from this blog

Android Tutorial

Android  is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a  linux-based Operating System ,  middleware  and  key mobile applications . It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices such as mobiles, tablets, televisions etc. This tutorial is developed for beginners and experienced persons. Let's see the topics of android that we are going to learn. Basics of Android In this fundamental chapter, you will learn about android, its components, how to create first android application, internal of first android application etc. What is Android History and Version Software Stack Core Building Blocks Android Emulator Installing softwares Setup Eclipse Hello Android example Internal Details Dalvik VM AndroidManifest.xml R.java Hide Title Bar Activity and I...

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM

CLOUD WORKFLOW SCHEDULING WITH DEADLINE AND TIME SLOT ALGORITHM Abstract Allocating service capacities in cloud computing is based on the assumption that they are unlimited and can be used at any time. However, available service capacities change with workload and cannot satisfy users’ requests at any time from the cloud provider’s perspective because cloud services can be shared by multiple tasks. Cloud service providers provide available time slots for new user’s requests based on available capacities. In this paper, we consider workflow scheduling with deadline and time slot availability in cloud computing. An iterated heuristic framework is presented for the problem under study which mainly consists of initial solution construction, improvement, and perturbation. Three initial solution construction strategies, two greedy- and fair-based improvement strategies and a perturbation strategy are proposed. Different strategies in the three phases result in several heuristics. ...

MobiContext: A Context-aware Cloud-Based Venue Recommendation Framework

            MobiContext: A Context-aware Cloud-Based Venue Recommendation Framework ABSTRACT  In recent years, recommendation systems have seen significant evolution in the field of knowledge engineering. Most of the existing recommendation systems based their models on collaborative filtering approaches that make them simple to implement. However, performance of most of the existing collaborative filtering-based recommendation system suffers due to the challenges, such as: (a) cold start, (b) data sparseness, and (c) scalability. Moreover, recommendation problem is often characterized by the presence of many conflicting objectives or decision variables, such as users’ preferences and venue closeness. In this paper, we proposed MobiContext , a hybrid cloud-based Bi-Objective Recommendation Framework (BORF) for mobile social networks. The MobiContext utilizes multi-objective optimization techniques to generate personalized recommendat...