Click here to Skip to main content
13,868,223 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

15.2K views
299 downloads
6 bookmarked
Posted 5 Oct 2014
Licenced CPOL

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

, 5 Oct 2014
Rate this:
Please Sign up or sign in to vote.
(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:

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

 

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

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.

//we  are initializing our <span style="font-size: 14px;">OnItemClickListener</span>
 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<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
 

 

	@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

<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 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

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)

Share

About the Author

Prilvesh K
Software Developer
Fiji Fiji
Prilvesh is a Front end and Back end developer who holds certificates from Google , Microsoft and Oracle who Specializes in Web development and automation using Python and PHP.
He has experience designing developing and building Api's and secure platforms that can handle enterprise level transactions with encryption.

He often simplifies complex problems and solves them through processes and procedures that are efficient and easily understandable even by non programmers including management.

You may also be interested in...

Comments and Discussions

 
GeneralThanks for the entry! Pin
Kevin Priddle9-Oct-14 7:45
professionalKevin Priddle9-Oct-14 7:45 
GeneralRe: Thanks for the entry! Pin
Prilvesh K26-Oct-14 3:16
professionalPrilvesh K26-Oct-14 3:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 5 Oct 2014
Article Copyright 2014 by Prilvesh K
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid