Android Interview Questions - SPLessons

Android text to speech

Home > Lesson > Chapter 3
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Android text to speech

Android text to speech

Android text to speech allows you to convert text into voice. Besides this, it also allows you to speak text in various languages. Android TextToSpeech feature is included in API Level 4. TextToSpeech class is used for this purpose. In order to use this class, you should instantiate an object of this class and also specify theinitListnere. In this lesson, we will explain you how to work with android text to speech or android speech synthesis. Also, we will teach you how to change the language type, pitch level and speed level. To implement TextToSpeech, first create MainActivity.java in your project and then implement TextToSpeech.OnInitListener. If your activity implements this interface, you have to override OnInit() method. setLanguage() You can set the Language by calling the setLanguage() method.
textS.setLanguage(Locale.US);
setPitch() You can change the Pitch Rate by calling setPitch() method.
textS. setPitch(0.6);
setSpeechRate() You can change the Speed Rate by calling setSpeechRate() method.
textS. setSpeechRate(2);
MainActivity.xml: [java] public class MainActivity extends Activity implements TextToSpeech.OnInitListener { Context context; TextToSpeech textS; Button tts; EditText ed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //set activity content to external view setContentView(R.layout.activity_main); context=this; //find views by Id ed=(EditText)findViewById(R.id.editText1); tts=(Button)findViewById(R.id.button1); //create an instance of TextToSpeech class textS=new TextToSpeech(context, this); //on click tts tts.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String text = ed.getText().toString(); textS.speak(text, TextToSpeech.QUEUE_FLUSH, null); } }); } @Override public void onDestroy() { // Don't forget to shutdown tts! if (textS != null) { //stop tts on destroy textS.stop(); textS.shutdown(); } super.onDestroy(); } @Override public void onInit(int arg0) { // TODO Auto-generated method stub if (arg0 == TextToSpeech.SUCCESS) { int result = textS.setLanguage(Locale.US); if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) { Toast.makeText(context, "This language is not supported", Toast.LENGTH_LONG).show(); } else { tts.setEnabled(true); String text = ed.getText().toString(); textS.speak(text, TextToSpeech.QUEUE_FLUSH, null); } } else { } } } [/java] Create activity_main.xml under res/layout folder. activity_main.xml: [xml]