Android is providing a cool feature (from Android 1.6) called Text to Speech (TTS) which speaks the text in different languages. This tutorial explains how to work with android text to speech or android speech synthesis. In this tutorial i also explained changing the language type, pitch level and speed level.

Download Code

Below i provided video of the ouput.

I developed a simple interface with one input field and a button to trigger a event that will take text from input field and speaks out.

Android text to speech

1. Create a new project by going to File ⇒ New Android Project. and fill required details.
2. Implement your main Activity class from TextToSpeech.OnInitListener

public class AndroidTextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener {

3. Now add following code your class.

package com.androidhive.texttospeech;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidTextToSpeechActivity extends Activity implements
		TextToSpeech.OnInitListener {
	/** Called when the activity is first created. */

	private TextToSpeech tts;
	private Button btnSpeak;
	private EditText txtText;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		tts = new TextToSpeech(this, this);

		btnSpeak = (Button) findViewById(R.id.btnSpeak);

		txtText = (EditText) findViewById(R.id.txtText);

		// button on click event
		btnSpeak.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				speakOut();
			}

		});
	}

	@Override
	public void onDestroy() {
		// Don't forget to shutdown tts!
		if (tts != null) {
			tts.stop();
			tts.shutdown();
		}
		super.onDestroy();
	}

	@Override
	public void onInit(int status) {

		if (status == TextToSpeech.SUCCESS) {

			int result = tts.setLanguage(Locale.US);

			if (result == TextToSpeech.LANG_MISSING_DATA
					|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
				Log.e("TTS", "This Language is not supported");
			} else {
				btnSpeak.setEnabled(true);
				speakOut();
			}

		} else {
			Log.e("TTS", "Initilization Failed!");
		}

	}

	private void speakOut() {

		String text = txtText.getText().toString();

		tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
	}
}

4. Now run your project and test your app by entering some text in input filed.

Changing Language

You can change language to speak by using setLanguage() function. Lot of languages are supported like Canada, French, Chinese, Germany etc.,

tts.setLanguage(Locale.CHINESE); // Chinese language

Changing Pitch Rate

You can set speed pitch level by using setPitch() function. By default the value is 1.0 You can set lower values than 1.0 to decrease pitch level or greater values for increase pitch level.

tts.setPitch(0.6);

Changing Speed Rate

The speed rate can be set using setSpeechRate(). This also will take default of 1.0 value. You can double the speed rate by setting 2.0 or make half the speed level by setting 0.5

tts.setSpeechRate(2);
This is image is for thumbnail purpose
Android Text to Speech
Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Pingback: Android Text to Speech Tutorial | Mobile | Syngu()

  • Chiraz20742

    converting handwritting to machine text is a whole other technology called OCR (Optical Character Recognition) … there are plenty of OCR engines out there that you can try out. Just Google “OCR”

  • Guest_120512

    Hey Ravi,
    Nice job man… I used this tts in my app and Great !! Thanks.

  • Astrogeek14

    Hello Ravi I’m new to Android and It is giving me a “import cannot be resolved” error umong all your variables being unresolved. how to I fix this????

  • Qmex_cool

    hi ravi…
    I want to create an app that can change the menu in android in the form of voice, how?
    please help me

  • Qmex_cool

    hi ravi…
    I want to create an app that can change the menu in android in the form of voice, how?
    please help me

  • marcusdev

    you can also save the output to a file

  • Hemachand

    Hello,

    I’m Hemachand. I’m new to android apps development. I would like to develop android app for one of our company social networking website: http://www.stockoy.com. So if any one of you having an idea how to develop app using PHP please let me know through my mail: chanduravilla@techie.com.

  • Durga Shankari

    Can we give book as input

    • Chandu Ravilla

      You can provide me please….

  • Durga Shankari

    Import cannot be resolved occurs due to some error in import. Press ctrl+o to import all the files

  • Sys_razor

    hi ravi.. how to add other languange and voice
    ‘?

  • Ppparthpatel49

    can i change tone to mickey mouse ? is there any api available or not?

    • nanda

      wtf are you smoking man?

  • 123linslouis

    This android program not working in my Android device..my device is Galuxy S3

  • Edu Charm

    The Best…

  • Mollycat

    When nothing else need be removed or added. This is so simple and obvious.

  • Rachna

    heartly thankx

  • Rachna

    sir m a bigger so pls post me some tutorials wd programs or app in android

  • Yulius Hari S

    Nicely done yet simple tutorial. Thank you Ravi, we really appreciate your work!
    Keep up the posting.

  • Pragnani

    How can you compare type of int with type of Boolean ? if (status == TextToSpeech.SUCCESS)

    • Pragnani

      Sorry it was wrong comment

  • Nik

    Simply better post….Thnk U Ravi

  • Koiky

    How to Change to Spanish Language??

    • max

      Locale locSpanish = new Locale(“spa”, “ESP”);
      int result = speech.setLanguage(locSpanish);

      • Rushik sutariya

        And how to set Hindi language

  • Luis

    Hi, excelent tutorial, I thought Text to Speech was difficult but it’s not. But I have a question, when i try to make a new project the app don’t work, but I downloaded your’s and it works, do you know where can I be making a mistake??

    Thank you!

  • Ass

    without a button right??

  • santosh

    nice tutorial bro.
    plz tell me hw to change voices like female voice defult to set but how to set male
    voice to speech text plz tel me bro i’ve urgent.

  • daniel

    nice and simple tutorial ravi ……. once again thanku for posting such a nice tutorial.

  • Mrs. guest

    I imported your code on 2.3 android telephone but ıt didn’t work, when ı tried english wors on the text side, does the fail occur because of the version the android? and how can I fix it? Could you help me please?

  • Maddie

    How can this code be changed to function without using implements
    TextToSpeech.OnInitListener directly on extends Activity?

    • youming2007

      You can write another class (for example: class A) which implements TextToSpeech.OnInitListener and implement necessary methods instead of doing it directly in Activity. After that, you initialize tts object by calling tts = new TextToSpeech(this, new A());

  • o

    it’s german not germany!!

  • saiede

    Hello., I’m trying to write a program that uses the output “speach to text”..And those words in a database search programs trying to help me.

  • vinod singh

    nice tutorial……….thnx a lot dude

  • Guest

    I am implementing an multilingual app which will translate text to the language based on the setting set in the phone. How can I use text to speech to speech based on the phone setting?

  • Pari

    nice tutorial… Thanks Ravi
    I have two questions:
    1. how can I control the speed?
    2. I want to use this tutorial for phone number but in some devices it says like a huge number, how can I fix it? Thanks again

  • Guest

    How can i use it to speech malay and tamil?

  • Kira00

    Doesn’t seem to work for Android 4 🙁

    • Leo Muñoz

      I have problems with speed anfd pitch in Android 4, but TTS code and language change works fine

  • george

    Hi all. I am a novice in developing app and thanks to
    Ravi for all good work that is doing . I’m working at a simple app and I get
    stuck . if you have knowledge of
    building android apps, and make team
    with me please replay to George.celsie@gmail.com . Thanks ang
    good luck for all your projects.

  • Sabik

    Thanks

  • Sororon

    So far this is best tutor i’ve met.
    right now i’m developing this program,but getting a problem.
    how could i make it speak in japanese language?

    i already do some trial and error like this one :
    tts.setLanguage(Locale.JAPANESE);

    or this one :
    Locale JPN = new Locale(“JAPAN”, “JAPANESE”);
    int result = tts.setLanguage(JPN);

    thanks for advance :))

  • khaoula

    How to Change the language to Arabic?

  • Florent1510

    Hello! Do you know how it would be possible to make an “ok Google”-like listener into an activity?
    Thanks!

  • asma

    How can i Change the language to french?

  • Me

    Is possible to load OnInit metod async? Because when i make activity which implements TTS and opening this activity app looks like freezed.

  • Alex Boey

    Awesome Tutorial!!!!

  • Abdul Rahman Majeed

    how can i use it in baseadapter ??

  • fuck me too

    Can you give me the list of supported languages?

    • Dzhuneyt

      Dutch, English (India), English (United Kingdom), English (United States), French, German, Italian, Korean, Polish, Portuguese (Brazil), Russian, Spanish (Spain), Spanish (United States).

      Taken from the Google Text to Speech app description here: https://play.google.com/store/apps/details?id=com.google.android.tts&hl=en

      However, it is always a safe bet to check if the language exists and is enabled and provide a fallback.

  • Darshit

    when i am clicking on “speak out” button on LogCat it comes that -> speak fail: not bound to TTS engine….I don’t know how to resolve this problem…Please some one help me out in this.

  • Hi, when I rotate the phone the speech stops, is it possible to prevent it without creating a background service for the TTS engine?

    • Leo Muñoz

      Yo have to put

      android:screenOrientation=”portrait”

      on the TTS activity´s Android Manifest to prevent sceen rotationon that activity.
      Use lnadscape instead of portrait if you want to use your app in horizontal position.
      That command will lock the screen in one way or another.

      Hope it suits you.

  • Najib Akbar

    i like this apps,

    I have a problem about the number of words from the library android tts.
    so I beg the info from the admin about the number of words / sentences from library
    to email me najibnadha@gmail.com
    thank you for your help.

  • Jatinder Singh

    unfortunately tts is stopped

    is received when tts is reading text and back button is pressed.Tried using

    if (tts != null) {
    tts.stop();
    tts.shutdown();
    }
    in on back pressed method but problem is not solved. Still app crashes

  • jerom

    the app works if i have earphone connected to the phone, i can here the sound in the earphone but not on my phone speaker(it works completely fine with another app which has similar functionality)

    • BillyTheKid

      EDIT: It wasn’t working for me as well. Not sure if you already solved it, but to me the problem was that the “Media” volume was muted. When changing the phone volume, generally the volume bar and a small gear will appear. Clicking the gear icon allows you to change the volume configuration for other options (ringtone, media, notifications, etc).

      • jerom

        try this it worked for me

        txtText = (EditText) findViewById(R.id.txtText);

        AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        int amStreamMusicMaxVol = audioManager.getStreamMaxVolume(audioManager.STREAM_MUSIC);

        audioManager.setStreamVolume(audioManager.STREAM_MUSIC, amStreamMusicMaxVol, 0);

        audioManager.setSpeakerphoneOn(true);

        // button on click event

        btnSpeak.setOnClickListener(new View.OnClickListener()

  • jerom

    the tts works fine but how can we load it faster, so that it doesnot cause delay when text input is given for conersion

  • monica

    How to build the TTS for own database or voice? Please help me

  • Zeeshan

    How can i use this functionality without having any interface ? I am developing a app for visually Impaired persons , i just need to generate a voice alert, and the text (alert will be hard coded).
    Can anyone help me with this ?
    I am getting error on this
    TextToSpeech.OnInitListener ….. Is interface is necessory for this ?

  • Pankit Mistry

    Hey, nice tutorial.

    I would like to know how we can change voice according to gender.
    Would be great if you can clarify about this point.

    • Faxriddin

      Hi. I need a TTS. But I can not find good example, es I have few TTS example butt these voice is not perfect. Did you find good text to speach example.

  • Dhaarani S

    I’m working with android studio project and my application is basedon text to speech but in my code speech is not audible but notification is there
    is there any solution

  • silvanas

    i using this code in main_activity it’s work well but when using it in a fragment of ViewPager it’s goes to force close, is there any solution …?

  • pradeepkumar reddy

    tts.speak() is depreccated

  • Chethan Kumar K

    Hey. How do i download the source code? Whenever i click on the ‘Download Code’ link and try to login using one of the available options, it just does not happen. Please help me out with it

  • Manisha Khatke

    failed to speak large amount of word….
    How to use large amount of word????

  • John Webster

    Always gives AndroidTextToSpeech has stopped

  • amit patel

    Is it possible speakOut() with arabic language ?

  • Gowtham M

    Hi sir,
    I have a spinner add two language like English,Hindi,if select English voice over should speech in English,if i select as a Hindi voice over should be in Hindi how to make please me sir………………

  • Farrukh Saleem

    hi every one.
    Sir I want to create a login page with the help of speech to text.

    for example:

    when I say action user name(john) okay then it catch john and write it in user name field.

    when I say action password (123) okay then it catch 123 and write it in the password field.

    When I say action it should start listening voice and when I say okay then it should stop listening voice.

    kindly guide me.
    i am android beginner

  • Kalyan Kumar

    sir can you upload the newer version of the code with current android studio version because your code is not working anymore for newer version

  • rk android

    Hello Mr. Ravi can you tell me how can i display each speaking word in toast or in textview in TTS ?

      • Farrukh Saleem

        Hello Ravi Sir.
        i am posting my problem above also but ignore above problem and answer this one only please.
        please help me i am so confused i complete my final year project but i have a problem.
        i want to mic on when my application is on and when my application is turned off then mic should off. but i have no idea about it please guide me
        this is my final year project and its my extra semester so please guide me about this problem

        • Turn on Mic in onResume() method and turn it off in onPause() method.

          • Farrukh Saleem

            thanks sir

          • Farrukh Saleem

            it not work sir
            kindly tell me other solution

          • Give the code you have tried.

          • Farrukh Saleem

            sir this is my code please check it and give me solution thanks

          • Farrukh Saleem

            sir i am sending you my code but after some time my code is deleted

          • Farrukh Saleem

            kindly sir guide me

  • Farrukh Saleem

    Hi every one how are you.
    i am crating a speech to text application and i want to keep mic on always.
    any body guide me please

  • Farrukh Saleem

    Hello Mr.Ravi Tamada
    can you tell me how can turn on mic always in speech to text????