Android Text-to-Speech

0
32

Android Text-to-Speech | Hello Developers, Hope our posts at mytrendin are valuable for you.In this tutorial, you would learn about Text to Speech.

What is Text to Speech?

A Text to Speech Synthesizes speech from the Text for immediate playback or to create a sound file.

A TextToSpeech instance can only be used to synthesize text once it has completed its initialization. Implement the TextToSpeech.OnInitListener to be notified of the completion of the initialization. When you are done using the TextToSpeech instance, call the shutdown() method to release the native resources used by the TextToSpeech engine. Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Working with Text to Speech

Creating New Project  – LaunchApps

Step 1: – Creating Project

Open your Android Studio -> Create a new project -> Choose EmptyActivity > Finish

Step 2:- Creating activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:transitionGroup="true"
android:background="@android:color/holo_green_light">

<TextView android:text="TEXT-O-SPEECH" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textview"
android:textSize="35dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textColor="@android:color/background_dark" />

<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_marginTop="46dp"
android:hint="Enter Text"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="@android:color/holo_red_light"
android:textColorHint="@android:color/holo_red_light" />

<Button
android:layout_height="wrap_content"
android:text="SPEECH CONVERSION"
android:id="@+id/b1"
android:layout_marginTop="27dp"
android:background="@android:drawable/button_onoff_indicator_on"
android:backgroundTint="@android:drawable/button_onoff_indicator_on"
android:layout_below="@+id/editText"
android:layout_width="650dp" />

<Button
android:text="LISTEN ACCENTS"
android:layout_height="wrap_content"
android:id="@+id/b2"
android:background="@android:drawable/button_onoff_indicator_on"
android:layout_below="@+id/b1"
android:layout_alignLeft="@+id/b1"
android:layout_alignStart="@+id/b1"
android:layout_width="650dp" />

<Button
android:text="CHANGE SETTINGS"
android:layout_height="wrap_content"
android:id="@+id/button1"
android:background="@android:drawable/button_onoff_indicator_on"
android:layout_below="@+id/b2"
android:layout_width="650dp" />

<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/imageView"
android:src="@drawable/tts"
android:theme="@style/Base.TextAppearance.AppCompat"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>

 

Step 3:- Creating MainActivity.java

In MainActivity.java, TextToSpeech.OnInitListener is implemented, Text To Speech is initialized, onInit method is Overridden, Finally, the text is Spoken out through speakOut() method and Inside onDestroy method is used to release the native resources used by the Text To Speech engine.

package com.example.kartiksakhuja.text_0_speech;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {
    TextToSpeech t1;
    EditText ed1;
    Button b1,b2,b3;
    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initializeControls();
        t1 = new TextToSpeech(this,this);
    }
    private void initializeControls(){
        ed1=(EditText)findViewById(R.id.editText);
        b1=(Button)findViewById(R.id.b1);
        b2=(Button)findViewById(R.id.button1);
        b3=(Button)findViewById(R.id.b2) ;
        imageView=(ImageView)findViewById(R.id.imageView);



        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speakOut();
            }
        });
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClass(MainActivity.this,Main3Activity.class);
                startActivity(i);
            }
        });
        b3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent= new Intent();
                intent.setClass(MainActivity.this,Main2Activity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    public void onInit(int status){
        if (status == TextToSpeech.SUCCESS) {

            int result = t1.setLanguage(Locale.ENGLISH);

            if (result == TextToSpeech.LANG_MISSING_DATA
                    || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            } else {

                b1.setEnabled(true);

                speakOut();
            }
        } else {

            Toast.makeText(getBaseContext(), "TTS execution Failed!", Toast.LENGTH_SHORT).show();
        }

    }
    private void speakOut() {
        String text = ed1.getText().toString();
        t1.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    @Override
    public void onDestroy() {
        if (t1 != null) {
            t1.stop();
            t1.shutdown();
        }
        super.onDestroy();
    }
}

 Step 4 :- Creating activity_main2.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:background="@android:color/holo_green_light"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:transitionGroup="true"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TRY OUT DIFFRENT ACCENTS!"
        android:textSize="35dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />



    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Enter Text"
        android:textColor="@android:color/holo_red_light"
        android:textColorHint="@android:color/holo_red_light"
        android:layout_below="@+id/textview"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:layout_above="@+id/b1" />

    <Button
        android:id="@+id/b1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="US ACCENT"
        android:layout_above="@+id/b2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:id="@+id/b2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/b3"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="CANADIAN_FRENCH ACCENT" />

    <Button
        android:id="@+id/b3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/b4"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="GERMAN ACCENT" />

    <Button
        android:id="@+id/b4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="ITALIAN ACCENT"
        android:layout_above="@+id/b5"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:id="@+id/b5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="37dp"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="JAPANESE ACCENT" />

    <Button
        android:id="@+id/b6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentStart="true"
        android:background="@android:drawable/button_onoff_indicator_on"
        android:text="CHINESE ACCENT" />

</RelativeLayout>

 

Step 5: -Creating Main2Activity.java

In Main2Activity.java, different Text to speech are initialised and each of them is set to a different language through Locale.

package com.example.kartiksakhuja.text_0_speech;

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

import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Main2Activity extends Activity {
TextToSpeech t1, t2, t3, t4, t5, t6;
EditText ed1;
Button b1, b2, b3, b4, b5, b6;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ed1 = (EditText) findViewById(R.id.editText);
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b3 = (Button) findViewById(R.id.b3);
b4 = (Button) findViewById(R.id.b4);
b5 = (Button) findViewById(R.id.b5);
b6 = (Button) findViewById(R.id.b6);
}

{

t1 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t1.setLanguage(Locale.US);
}
}
});
t2 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t2.setLanguage(Locale.CANADA_FRENCH);
}
}
});
t3 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t3.setLanguage(Locale.GERMANY);
}
}
});

t4 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t4.setLanguage(Locale.ITALY);
}
}
});
t5 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t5.setLanguage(Locale.JAPAN);
}
}
});
t6 = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()

{
@Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
t6.setLanguage(Locale.CHINA);
}
}
});


b1.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t1.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
b2.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t2.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
b3.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t3.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
b4.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t4.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}
});
b5.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t5.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

}
});
b6.setOnClickListener(new View.OnClickListener()

{
@Override
public void onClick(View v) {
String toSpeak = ed1.getText().toString();
t6.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);
}

});
}
public void onPause() {
if (t1 != null) {
t1.stop();
t1.shutdown();
}
if (t2 != null) {
t2.stop();
t2.shutdown();
}
if (t3 != null) {
t3.stop();
t3.shutdown();
}
if (t4 != null) {
t4.stop();
t4.shutdown();
}
if (t5 != null) {
t5.stop();
t5.shutdown();
}if (t6 != null) {
t6.stop();
t6.shutdown();
}
super.onPause();
}
}

Related:

Text to Speech and Speech to Text Using Google API and Navigation Drawer Activity

Android Real Time Face detection and Prediction using Google Mobile Vision API

Image Recognition Using Google’s API

Encryption using Java Android Cryptography API

Parsing the Json Data using Android Retrofit Api and display in Recyclerview with Cardview

Step 6:-Creating activity_main3.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
android:orientation="vertical"
android:background="@android:color/holo_green_light"
android:weightSum="1">

<TextView
android:text="SET DIFFERENT PITCHES AND SPEECH RATES!"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:textColorHighlight="@android:color/black"
android:textColorHint="@android:color/black"
android:textColorLink="@android:color/black"
android:textCursorDrawable="@android:color/black" />

<TextView
android:id="@+id/tVSpeechRate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Speech Rate"
android:layout_above="@+id/sBSpeechRate"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<SeekBar
android:id="@+id/sBSpeechRate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="19"
android:progress="9"
android:layout_above="@+id/tVPitchRate"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="11dp"
android:layout_marginEnd="11dp" />

<TextView
android:id="@+id/tVPitchRate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set Pitch"
android:layout_above="@+id/sBPitchRate"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />

<SeekBar
android:id="@+id/sBPitchRate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:max="19"
android:progress="9"
android:layout_above="@+id/btnSpeak"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="65dp" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Enter Text"
android:textColor="@android:color/holo_red_light"
android:textColorHint="@android:color/holo_red_light"
android:textColorLink="@android:color/holo_red_light"
android:layout_weight="0.33"
android:layout_above="@+id/tVSpeechRate"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="26dp" />

<Button
android:id="@+id/btnSpeak"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SPEECH CONVERSION"
android:background="@android:drawable/button_onoff_indicator_on"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="48dp" />

</RelativeLayout>

 

Step 7: -Creating Main3Activity.java

In Main3Activity.java, two seekbars are used to change PitchRate and SpeechRate where min. and max. are set to 9 and 19 respectively.

package com.example.kartiksakhuja.text_0_speech;

import java.util.Locale;

import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.speech.tts.TextToSpeech;

public class Main3Activity extends Activity implements TextToSpeech.OnInitListener {
double pitch = 0.0f, speechRate = 0.0f;

private TextToSpeech tts;
SeekBar sBSpeechRate, sBPitchRate;
EditText editText;
Button btnSpeak;
TextView tVSpeechRate, tVPitchRate;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
initializeControls();
tts = new TextToSpeech(this, this);
}
private void initializeControls() {
sBSpeechRate = (SeekBar) findViewById(R.id.sBSpeechRate);
sBPitchRate = (SeekBar) findViewById(R.id.sBPitchRate);
editText = (EditText) findViewById(R.id.editText);
btnSpeak = (Button) findViewById(R.id.btnSpeak);
tVSpeechRate = (TextView) findViewById(R.id.tVSpeechRate);
tVPitchRate = (TextView) findViewById(R.id.tVPitchRate);
sBSpeechRate.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
speechRate = ((double) progress + 1) / 10;
}
});

sBPitchRate.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}

@Override
public void onStartTrackingTouch(SeekBar seekBar) {

}

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
pitch = ((double) progress + 1) / 10;
}
});

btnSpeak.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
speakOut();
}
});
}

@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
} else {

btnSpeak.setEnabled(true);

speakOut();
}

} else {

Toast.makeText(getBaseContext(), "TTS execution Failed!", Toast.LENGTH_SHORT).show();
}

}
private void speakOut() {
String text = editText.getText().toString();
tts.setPitch((float) pitch);
tts.setSpeechRate((float) speechRate);
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}

Here, is the default manifest file:-

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kartiksakhuja.text_0_speech">

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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

</manifest>

 

Outputs:-

  

Thanks for following our tutorials.If you have any queries fell free to ask us in the comment section.Do not forget to Subscribe for all the latest technical happenings. If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

LEAVE A REPLY

Please enter your comment!
Please enter your name here