Skip to main content

Text To Speech - Android Tutorial


This tutorial explains how to work with android text to speech or android speech synthesis. Also explained changing the language type, pitch level and speed level.

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.







Now follow the coding to develop this simple application



1. tts_layout.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".TextToSpeechActivty" 
    android:background="@drawable/ddd">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        style="@style/Button"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="75dp"
        android:text="Speak" 
        android:textColor="@color/black"/>

    <EditText
        android:id="@+id/inputText"
        style="@style/EditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="221dp"
        android:ems="10"
        android:gravity="bottom" >

        <requestFocus />
    </EditText>

</RelativeLayout>



2. Add the following code in your class.



/**

 * Reads the input value from the user and converts into voice.
 */
public class TextToSpeechActivity extends Activity implements
TextToSpeech.OnInitListener {
private TextToSpeech textToSpeech;
private Button button;
private EditText inputText;

/**
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tts_layout);
button = (Button) findViewById(R.id.button1);
inputText = (EditText) findViewById(R.id.inputText);
textToSpeech = new TextToSpeech(this, this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
convertTextToSpeech();
}

});
convertTextToSpeech();
}

/**
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tts_layout, menu);
return true;
}

/**
* a callback to be invoked indicating the completion of the TextToSpeech
* engine initialization.
* @see android.speech.tts.TextToSpeech.OnInitListener#onInit(int)
*/
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
convertTextToSpeech();
}
} else {
Log.e("error", "Initilization Failed!");
}
}

/**
* Releases the resources used by the TextToSpeech engine. It is good
* practice for instance to call this method in the onDestroy() method of an
* Activity so the TextToSpeech engine can be cleanly stopped.
* @see android.app.Activity#onDestroy()
*/
@Override
public void onDestroy() {
textToSpeech.shutdown();
}

/**
* Speaks the string using the specified queuing strategy and speech
* parameters.
*/
private void convertTextToSpeech() {
String text = inputText.getText().toString();
if (null == text || "".equals(text)) {
text = "Please give some input.";
}
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}



NOTE: Use the library android-support-v4.jar 


Changing Language

You can change language to speak by using setLanguage() function. Lot of languages are supported like Canada, French, Chinese, Germany etc.,
textToSpeech.setLanguage(Locale.US);   // English 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.

textToSpeech.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.
textToSpeech.setSpeechRate(2);



________________________________________________________

Source code for this application texttospeech.zip

Comments

Post a Comment

Popular posts from this blog

Zoom Image - Android Tutorial

Here we are going to see how to zoom an image in Imageview Will see it through a sample 1. Create xml with an ImageView <? xml version="1.0" encoding="utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout       xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     tools:context=".MainActivity" >     < LinearLayout         android:layout_width="200dp"         android:layout_height="200dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintLeft_toLeftOf="parent"         app:layout_constraintRight_toRightOf="parent"    ...

Add custom font in Android using Calligraphy library

Are you fed up of Custom Views to set fonts? Or traversing the ViewTree to find TextViews? Sometime we want some other font for our Android application then you can add custom font in Android using Calligraphy library . Dependency Include the dependency Download (.aar) dependencies { compile ‘uk.co.chrisjenx:calligraphy:2.2.0’ } Add Fonts Add your custom fonts to assets/ . All font definitions are relative to this path. On Assets you should right-click New Directory, call it "fonts". In the finder put the .ttf  or .otf  font files in there. Create Class Create a class that extends Application and write this code public class App extends Application { @Override public void onCreate() { super.onCreate(); CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("your font path") .setFontAttrId(...

Bluetooth Chat Application - Android Tutorial

In this tutorial, we will see about how to design an Android layout for chat application using Chat Bubbles  and the main part is chat via Bluetooth . Main objective of this post is to give an idea about how to allow two-way text chat over Bluetooth in android. Bubbles: Chat bubbles are background image that expands horizontally and vertically as required based on the message posted. Bubbles are Nine-patch Images. Image Nine-patch Image In creating Android chat bubbles, nine-patch image plays a crucial role.  Nine-patch image  is a bitmap which stretches to fit the content posted in the View where it is applied as a background. A NinePatch drawable is a standard PNG image that includes an extra 1-pixel-wide border. It must be saved with the extension  .9.png , and saved into the  res/drawable/  directory of your project. The border is used to define the stretchable and static areas of the image. You indicate a stretchable section ...