Thursday, October 1, 2015

How to use text to speech in android

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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:fitsSystemWindows="true"
    tools:context=".MainActivity"
    >
    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay"
        >
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay"
            />
    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_dialog_email"
        />
</android.support.design.widget.CoordinatorLayout>
content_main.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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main"
    tools:context=".MainActivity"
    android:background="#e9e9e9"
    >
    <GridView
        android:id="@+id/gv"
        android:layout_width="650dp"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:verticalSpacing="2dp"
        android:horizontalSpacing="2dp"
        android:stretchMode="columnWidth"
        android:gravity="left"
        android:background="#e9e9e9"
        >
    </GridView>
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.kidsvoice;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements TextToSpeech.OnInitListener {
    private TextToSpeech tts;
    private GridView gv;
    public static int gridview_column_width = 150; // In pixels

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        gv = (GridView) findViewById(R.id.gv);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Set the GridView number of columns
        int num_columns = Math.round(getScreenWidth()/gridview_column_width);
        if(num_columns <=2){
            gv.setNumColumns(GridView.AUTO_FIT);
        }
        else {
            gv.setNumColumns(num_columns);
        }

        /*
            TextToSpeech
                Synthesizes speech from 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.
        */

        // Initialize a new TextToSpeech
        tts = new TextToSpeech(getApplicationContext(),this);

        // In this tutorial, we do not use the floating action button
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        /*fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/
        fab.hide(); // Hide the floating action button

        // Create a HashMap to hold color name value pairs
        Map<String,String> colors = new HashMap<>();
        colors.put("Blue","#0000FF");
        colors.put("Gray","#808080");
        colors.put("Green","#008000");
        colors.put("Black","#000000");
        colors.put("Indigo","#4B0082");
        colors.put("Orange","#FFA500");
        colors.put("Pink","#FFC0CB");
        colors.put("Purple","#800080");
        colors.put("Red","#FF0000");
        colors.put("Violet","#EE82EE");
        colors.put("White","#FFFFFF");
        colors.put("Yellow","#FFFF00");

        // Create an ArrayList for color names
        final List<String> colorNames = new ArrayList<>(colors.keySet());
        // Create an ArrayList for color values
        final List<String> colorValues = new ArrayList<>(colors.values());

        // Data bind GridView with ArrayAdapter
        gv.setAdapter(new ArrayAdapter<String>(
                this, android.R.layout.simple_list_item_1, colorNames) {
            public View getView(int position, View convertView, ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                final TextView tv = (TextView) view;

                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                        gridview_column_width,
                        gridview_column_width
                );
                tv.setLayoutParams(lp);
                tv.setGravity(Gravity.CENTER);
                tv.setTypeface(Typeface.SANS_SERIF, Typeface.NORMAL);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
                tv.setText(colorNames.get(position));
                final String currentColor = colorValues.get(position);
                tv.setBackgroundColor(Color.parseColor(currentColor));
                return tv; // Return the TextView as GridView item
            }
        });

        // Set an item click listener for GridView
        gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // Set background color animation
                ColorDrawable[] color = {new ColorDrawable(Color.WHITE),
                        new ColorDrawable(Color.parseColor(colorValues.get(position)))};
                TransitionDrawable trans = new TransitionDrawable(color);
                view.setBackground(trans);
                trans.startTransition(1000); // duration 3 seconds

                // Let speak the clicked color name
                String textToSpeak = colorNames.get(position);
                speakNow(textToSpeak);
            }
        });
    }

    @Override
    public void onDestroy(){
        if(tts!=null){
            /*
                public int stop ()
                    Interrupts the current utterance (whether played or rendered to file)
                    and discards other utterances in the queue.

                    Returns
                        ERROR or SUCCESS.
            */
            tts.stop();
            /*
                public void shutdown ()
                    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.
            */
            tts.shutdown();
        }
        super.onDestroy();
    }

    @Override
    public void onInit(int speechStatus){
        if(speechStatus == TextToSpeech.SUCCESS)
        {
            int speechResult = tts.setLanguage(Locale.US);
            if(speechResult == TextToSpeech.LANG_MISSING_DATA){
                Log.e("TTS", "Language not supported");
            }
            else {
                //speakNow();
                Log.e("TTS", "Language is ok.");
            }
        }else{
            Log.e("TTS", "Failed to initialize TextToSpeech service.");
            Toast.makeText(this, "Failed to speak.", Toast.LENGTH_SHORT).show();
        }
    }

    private void speakNow(String textToSpeak) {
        /*
            public int setPitch (float pitch)
                Sets the speech pitch for the TextToSpeech engine. This has no effect
                on any pre-recorded speech.

                Parameters
                    pitch : Speech pitch. 1.0 is the normal pitch, lower values lower the tone
                    of the synthesized voice, greater values increase it.

                Returns
                    ERROR or SUCCESS.
        */

        /*
            public int setSpeechRate (float speechRate)
                Sets the speech rate. This has no effect on any pre-recorded speech.

                Parameters
                    speechRate : Speech rate. 1.0 is the normal speech rate, lower values slow down the
                        speech (0.5 is half the normal speech rate), greater values accelerate it
                        (2.0 is twice the normal speech rate).

                Returns
                    ERROR or SUCCESS.
        */
        /*
            float pitch = 1.0f;
            float speed = 1.0f;
            tts.setPitch(pitch);
            tts.setSpeechRate(speed);
        */

        /*
            public int speak (CharSequence text, int queueMode, Bundle params, String utteranceId)
                Speaks the text using the specified queuing strategy and speech parameters, the
                text may be spanned with TtsSpans. This method is asynchronous, i.e. the method
                just adds the request to the queue of TTS requests and then returns. The synthesis
                might not have finished (or even started!) at the time when this method returns.
                In order to reliably detect errors during synthesis, we recommend setting an
                utterance progress listener (see setOnUtteranceProgressListener(UtteranceProgressListener))
                and using the KEY_PARAM_UTTERANCE_ID parameter.

                Parameters
                    text : The string of text to be spoken. No longer than
                        getMaxSpeechInputLength() characters.
                    queueMode : The queuing strategy to use, QUEUE_ADD or QUEUE_FLUSH.
                    params : Parameters for the request. Can be null. Supported parameter
                        names: KEY_PARAM_STREAM, KEY_PARAM_VOLUME, KEY_PARAM_PAN. Engine specific
                        parameters may be passed in but the parameter keys must be prefixed by the
                        name of the engine they are intended for. For example the keys
                        "com.svox.pico_foo" and "com.svox.pico:bar" will be passed to the engine
                        named "com.svox.pico" if it is being used.
                    utteranceId : An unique identifier for this request.

                Returns
                    ERROR or SUCCESS of queuing the speak operation.
        */

        /*
            public static final int QUEUE_FLUSH
                Queue mode where all entries in the playback queue (media to be played and text to
                be synthesized) are dropped and replaced by the new entry. Queues are flushed with
                respect to a given calling app. Entries in the queue from other callees are not discarded.

                Constant Value: 0 (0x00000000)
        */
        tts.speak(textToSpeak, TextToSpeech.QUEUE_FLUSH, null,null);
    }

    // Custom method to get the screen width in pixels
    public int getScreenWidth(){
        WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        Point size = new Point();
        //Display dimensions in pixels
        display.getSize(size);
        int width = size.x;
        //int height = size.y;
        return width;
    }
}


More android examples