Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

(Wildcard entry)Android Text to speech synthesis with Listview arrays with toast

5.00/5 (4 votes)
5 Oct 2014CPOL5 min read 23.9K   337  
(Wildcard entry)Android Text to speech synthesis with Listview arrays with toast

Introduction

Bula Vinaka (Hello) my name is Prilvesh and I am from Fiji islands.

I wrote a detailed article as part of the android competition (wildcard entry) on ( TTS) Synthesis but deu to unforseen error it never published ,But i am determined to emphasize the importance of Text to speech synthesis so i write again a basic summative guide.I hope as a beginner you will like it.
 

The purpose of this Tutorial is to emphasize the Importance of the Text to speech synthesis (TTS) function that is available on respective android devices .

Text to speech synthesis (TTS)  is a very powerful tool that is often overlooked by so many developers which if implemented in  your applications enhances the user experience and provides a certain level of elegance and sophistication to your applications.

Further more In very broad General terms one of the many advantages of  TTS object implementation is that it allows for facilitation of  :

  1. Iterative incremental interactive activities
  2. Mixed Learning methods
  3. conversion of text to synthesized Audio for the Blind.
  4. Minimization of storage space used on the tablet through elimination of static mp3,mp4,ogg formats through dynamic implementation of real time  Text to speech synthesis
  5. Learning and Development of Language and Translation of  speech  pronunciation.


Google text to speech settings


The best part about  Text to speech synthesis (TTS)  on Android is that as a beginner it is very easy  to implement, that is if you get help from the right information avenues 

So for the purpose of this beginners tutorial we will develop an Android activity that allows you to click on a list item , when the item is clicked the text is read out aloud.

Since the focus of this tutorial is for beginners we will not implement any error checking

To get technical we will

  1. Create a  Main activity  Java class and a corresponding XML Layout for the user interface
  2. Within the Main activity Java class we will:

 

  •  Import required Activity classes that extend our activities functionality for TTS initialization
  •  create  an  OnInitListener
  • *Declare and create Array of Static  elements  to populate  the Listview as Items .
  • Implement Overridden Methods
  • *Declare and Initialize the  Text to speech object and specify basic Parameters
  • *Create a simple Array adapter for the Listitem
  • *Implement an OnItemClickListener
  • *Finally call  the TTS speak function to read text based on  position of the selected index of the item.

How The app looks(Basic list)
Final application

Using the code

For the  purpouse of this tutorial We will be using the Eclipse IDE with ADT  SDK 20.

By now I assume you already have and IDE and android SDK installed but if you don’t than simply follow the steps located at the following Link to set up the Eclipse ADT environment.

http://www.instructables.com/id/Building-Your-First-Android-Application/?ALLSTEPS

 

So now the actual Tutorial begins:

In order to Use TTS  in your activity you only need to import  android.speech.tts.TextToSpeech; and  import android.speech.tts.TextToSpeech.OnInitListener;

If you wish to use Toast than you need to import  import android.widget.Toast;

So below is  the full list of classes that we will need to Import inorder to extend our activity:

Java
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

 

Previously  we just wrote down  all of the header classes that will be referred to .

Now we begin the actual implementation by creating a public class  called ListView App that extends the Activity with and OnInitListener

 

Java
public class ListviewApp extends Activity implements OnInitListener
{
   public int index;

//we created an  interger  named index  which will be usefull to determine the position of our item.
   
 public String []words= {"Bula","Vinaka","moce mada","kaiviti","dua","rua"};

//we created a string array called words which contains our static listitems  The language is FIJIAN lol
    
public String [] pronounciation= {"Boola","Vinaka","More They Maandaa","Kaiviti","dooah","rooah"};

//For the fun of it we created a string array called pronounciation which contains pronounciations for our listitems
 
   @Override
    public void onCreate(Bundle savedInstanceState) //next we create our override method  which is onCreate

    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview_app);
//we basically set the view of this activity to our layout xml called  listview_app

        final ListView lv =(ListView) findViewById(R.id.List);
// now we call  our listview item called lv  

//Now here comes the main part  if you wish to use TTS  you need to initialize the TTS OBJECT:

        final TextToSpeech tts = new TextToSpeech(this,this);
// We declare a text to speech object with a variable name of tts
       
tts.setLanguage(Locale.ENGLISH); // We set the Language to English.<code>
</code>
 //You can also Set Pitch, 1.0 is Normal   
//Lower values lower the tone of the synthesized voice, greater values increase it<code>.</code>
    tts.setPitch(0.8f);

    // You can also  Set Speech Rate, 1.0 is Normal
    //Lower values slow down the speech, greater values accelerate it
    tts.setSpeechRate(1.1f);

 

So fare uptill now you have created and array of words and pronounciation and initialized a speech to text object with language of English.

Next lets create an  simple adapter  that populates the array words in simple_list_item_1

Java
ArrayAdapter<string> array_adapter= new ArrayAdapter<string>(this,
                                             android.R.layout.simple_list_item_1,android.R.id.text1,
                                             words);

lv.setAdapter(array_adapter); //We are mapping lv (listview) to  our array adapter 


 </string></string>

Now lets make it work so far  our activity will only display a list how ever it will do anything when clicked ,so inorder to get it working we need to create an  OnItemClickListener so when a listitem is clicked 3 things are done firstly the corresponding index number position of the array is loaded secondly a toast is generated and lastly text is converted to speech.

Java
//we  are initializing our OnItemClickListener</span>
 lv.setOnItemClickListener(new OnItemClickListener(){
 
        public void onItemClick(AdapterView<!--?--> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            index= arg2;
            
           
^__strong>Toast.makeText(getApplicationContext(), words[index], Toast.LENGTH_SHORT).show(); 
//The item selected from the words array is toasted 
tts.speak(pronounciation[index], TextToSpeech.QUEUE_ADD, null);
//the item selected from the  pronouciation array is synthesized using the speak method<code>.</code>
           
            
tts.speak("haha man you just ran your first example ", TextToSpeech.QUEUE_ADD, null);
Toast.makeText(ListviewApp.this,"Become a friend www.facebook.com/prilvesh.k", Toast.LENGTH_LONG).show();}
 });
 } //just aword of advise becarefull of your curly brackets dont miss any !

Previously we learnt how to create an onlcik Listner to detect which listitem has been clicked and accordingly pass its valeu to our Toast method called maketext and Text to speech synthesis method tts.

Congrats your  ListviewApp.java class is now in working condition but we are not done yet.

Finally we move on to  creating an Overide method to check whether The text to speech sysnthesis is supported by a paticular device or not  ,If the TTS function is not present an error will occur so  we will notify the user by a toast.
To be honest we should have done this in the beginig but our main focus was on implementation and usage
 

 

Java
	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
	      // we check to see if text to speech is suppourted on the device 
	      if (status == TextToSpeech.SUCCESS)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Text-To-Speech SYNTHESIS engine is ready", Toast.LENGTH_SHORT).show();
	      }
	      
	      //If text to speech is not supported than we output an error message
	      else if (status== TextToSpeech.ERROR)
	      {
	     Toast.makeText(ListviewApp.this, 
	                  "Error occurred while initializing Text-To-Speech engine probably you dont have it installed", Toast.LENGTH_LONG).show();
	      }
		
	}

 

RECAP (SUMMARY)

OK SO NOW YOU ARE DONE !

But before you go  a small recap in 3 easy steps to implement Text to speech Synthesis

STEP1-Import the header files

import android.speech.tts.TextToSpeech;

import android.speech.tts.TextToSpeech.OnInitListener;

STEP2-Create a tts object

final TextToSpeech tts = new TextToSpeech(this,this);

 tts.setLanguage(Locale.ENGLISH);

STEP3-Call  the speak method  from a onclick listener

ttS.speak("THIS IS A TEXT TO SPEECH EXAMPLE THIS WILL BE SAID", TextToSpeech.QUEUE_FLUSH, null);

If the xml files do not show please download the sourcecode

Our XML for the UI named :activity_listview_app.xml

XML
<relativelayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">

    <listview android:id="@+id/List" android:layout_height="match_parent" android:layout_width="match_parent">
    </listview>

</relativelayout>

 

Our Manifest file named :AndroidManifest.xml

XML
<!--?xml version="1.0" encoding="utf-8"?-->
<manifest android:versioncode="1" android:versionname="1.0" package="com.example.listviewapp" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-sdk android:minsdkversion="8" android:targetsdkversion="17">

    <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
        <activity android:label="@string/app_name" android:name="com.example.listviewapp.ListviewApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN">

                <category android:name="android.intent.category.LAUNCHER">
            </category></action></intent-filter>
        </activity>
    </application>

</uses-sdk></manifest>


 

Finally our activity file named :ListviewApp.java

Java
package com.example.listviewapp;

import java.util.Locale;


import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;




public class ListviewApp extends Activity implements OnInitListener
{
   public int index; 
// we created an  interger  named index  which will be usefull to determine the position of our item.
    public String []words= {"Bula","Vinaka","moce mada","kaiviti","dua","rua"};
//we created a string array called words which contains our static listitems  The language is FIJIAN lol
    public String [] pronounciation= {"Boola","Vinaka","More They Maandaa","Kaiviti","dooah","rooah"};
//For the fun of it we created a string array called pronounciation which contains pronounciations for our listitems
    @Override
    public void onCreate(Bundle savedInstanceState) //next we create our override method  which is onCreate

    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listview_app); 
//we basically set the view of this activity to our layout xml called  listview_app

        final ListView lv =(ListView) findViewById(R.id.List);
 
        final TextToSpeech tts = new TextToSpeech(this,this);
        tts.setLanguage(Locale.ENGLISH);
        tts.setPitch(0.8f);
        tts.setSpeechRate(1.1f);
 
        ArrayAdapter<string> array_adapter= new ArrayAdapter<string>(this,
                                                          android.R.layout.simple_list_item_1,
                                                                     android.R.id.text1,
                                                                     words);
 
       lv.setAdapter(array_adapter);
 
       lv.setOnItemClickListener(new OnItemClickListener(){
 
        public void onItemClick(AdapterView<!--?--> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
            index= arg2;
            
           
            Toast.makeText(getApplicationContext(), words[index], Toast.LENGTH_SHORT).show(); 
//The item selected from the words array is toasted 
            tts.speak(pronounciation[index], TextToSpeech.QUEUE_ADD, null);
//the item selected from the  pronouciation array is synthesized using the speak method.
           
            
           tts.speak("haha man you just ran your first example ", TextToSpeech.QUEUE_ADD, null);
           Toast.makeText(ListviewApp.this, 
	                  "Become a friend www.facebook.com/prilvesh.k", Toast.LENGTH_LONG).show();
        }
        
    });
 
      }

	@Override
	public void onInit(int status) {
		// TODO Auto-generated method stub
	      // we check to see if text to speech is suppourted on the device 
	      if (status == TextToSpeech.SUCCESS)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Text-To-Speech SYNTHESIS engine is ready", Toast.LENGTH_SHORT).show();
	      }
	      
	      //If text to speech is not supported than we output an error message
	      else if (status== TextToSpeech.ERROR)
	      {
	          Toast.makeText(ListviewApp.this, 
	                  "Error occurred while initializing Text-To-Speech engine probably you dont have it installed", Toast.LENGTH_LONG).show();
	      }
		
	}


}

</string></string>

Points of Interest

If you want an in depth tutorial on Fragments and Listviews have a look at www.codeproject.com/Articles/820353/Create-an-app-for-Phone-and-Tablet

For the TTS API and functionality refer to http://developer.android.com/reference/android/speech/tts/TextToSpeech.html

THANK YOU   THE END !

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)