Android Speech To Text Tutorial

Android comes with an inbuilt feature android speech to text through which you can provide speech input to your app. In this tutorial we will learn how to make speech to text converter. So as the name implies, user voice will be converted into text and shown on Android Screen. As soon as a user say something, Android will recognize his/her voice and convert it into text. It will do it through RecognizerIntent.

Android Speech To Text Tutorial

Download projct file of  Android Speech To Text Tutorial – Android Studio

I have created a simple app to demonstrate this tutorial. Below is the screenshot of the app which contains a simple button to invoke speech input and a TextView to display the converted speech text.

Speech to text

1. As we will recored audio to convert it into text so we will need RECORD_AUDIO permission into our AndroidManifest.xml

<uses-permission android:name="android.permission.RECORD_AUDIO"/>

Our AndroidManifest.xml  file look like this,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.andrious.speechtotext">
    <uses-permission android:name="android.permission.RECORD_AUDIO"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>
    </application>

</manifest>

2. Add this  image in drawable and remane it mic .

3. Our activity_main.xml looks like this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#3F51B5">

    <TextView
        android:id="@+id/txtSpeechInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:textSize="26sp"
        android:textStyle="normal"
        android:textColor="#FFFFFF"/>

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"/>

    <ImageButton
        android:id="@+id/SpeakButton"
        android:layout_width="90dp"
        android:layout_height="90dp"
        android:scaleType="fitXY"
        android:background="@android:color/transparent"
        android:src="@drawable/mic"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"/>

</RelativeLayout>

4. This is the main part of voice recognition app where we will use RecognizerIntent to convert speech into text. Add following code in MainActivity.java:

package com.andrious.speechtotext;

        import android.Manifest;
        import android.content.Context;
        import android.content.Intent;
        import android.content.pm.PackageManager;
        import android.os.Build;
        import android.os.Bundle;
        import android.speech.RecognitionListener;
        import android.speech.RecognizerIntent;
        import android.speech.SpeechRecognizer;
        import android.support.v4.app.ActivityCompat;
        import android.support.v7.app.AppCompatActivity;
        import android.util.Log;
        import android.view.View;
        import android.view.Window;
        import android.view.WindowManager;
        import android.widget.ImageButton;
        import android.widget.ProgressBar;
        import android.widget.TextView;

        import java.util.ArrayList;

/**
 * Created by ISRAFIL MAHMUD RAJU on 1/2/2018.
 */

public class MainActivity extends AppCompatActivity implements RecognitionListener {

    private TextView returnedText;
    ImageButton recordbtn;
    private ProgressBar progressBar;
    private SpeechRecognizer speech = null;
    private Intent recognizerIntent;
    static final int REQUEST_PERMISSION_KEY = 1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);
        returnedText = (TextView) findViewById(R.id.txtSpeechInput);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        recordbtn = (ImageButton) findViewById(R.id.SpeakButton);

        String[] PERMISSIONS = {Manifest.permission.RECORD_AUDIO};
        if(!Function.hasPermissions(this, PERMISSIONS)){
            ActivityCompat.requestPermissions(this, PERMISSIONS, REQUEST_PERMISSION_KEY);
        }


        progressBar.setVisibility(View.INVISIBLE);
        speech = SpeechRecognizer.createSpeechRecognizer(this);
        speech.setRecognitionListener(this);
        recognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE,
                "en");
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
                this.getPackageName());
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);

        /*
        Minimum time to listen in millis. Here 5 seconds
         */
        recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 5000);
        recognizerIntent.putExtra("android.speech.extra.DICTATION_MODE", true);




        recordbtn.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View p1)
            {
                progressBar.setVisibility(View.VISIBLE);
                speech.startListening(recognizerIntent);
                recordbtn.setEnabled(false);

                /*To stop listening
                    progressBar.setVisibility(View.INVISIBLE);
                    speech.stopListening();
                    recordbtn.setEnabled(true);
                 */
            }


        });



    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (speech != null) {
            speech.destroy();
            Log.d("Log", "destroy");
        }

    }

    @Override
    public void onBeginningOfSpeech() {
        Log.d("Log", "onBeginningOfSpeech");
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onBufferReceived(byte[] buffer) {
        Log.d("Log", "onBufferReceived: " + buffer);
    }

    @Override
    public void onEndOfSpeech() {
        Log.d("Log", "onEndOfSpeech");
        progressBar.setVisibility(View.INVISIBLE);
        recordbtn.setEnabled(true);
    }

    @Override
    public void onError(int errorCode) {
        String errorMessage = getErrorText(errorCode);
        Log.d("Log", "FAILED " + errorMessage);
        progressBar.setVisibility(View.INVISIBLE);
        returnedText.setText(errorMessage);
        recordbtn.setEnabled(true);
    }

    @Override
    public void onEvent(int arg0, Bundle arg1) {
        Log.d("Log", "onEvent");
    }

    @Override
    public void onPartialResults(Bundle arg0) {
        Log.d("Log", "onPartialResults");

        ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        String text = "";
        /* To get all close matchs
        for (String result : matches)
        {
            text += result + "\n";
        }
        */
        text = matches.get(0); //  Remove this line while uncommenting above    codes


        returnedText.setText(text);
    }

    @Override
    public void onReadyForSpeech(Bundle arg0) {
        Log.d("Log", "onReadyForSpeech");
    }

    @Override
    public void onResults(Bundle results) {
        Log.d("Log", "onResults");

    }

    @Override
    public void onRmsChanged(float rmsdB) {
        Log.d("Log", "onRmsChanged: " + rmsdB);
        progressBar.setProgress((int) rmsdB);

    }

    public static String getErrorText(int errorCode) {
        String message;
        switch (errorCode) {
            case SpeechRecognizer.ERROR_AUDIO:
                message = "Audio recording error";
                break;
            case SpeechRecognizer.ERROR_CLIENT:
                message = "Client side error";
                break;
            case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
                message = "Insufficient permissions";
                break;
            case SpeechRecognizer.ERROR_NETWORK:
                message = "Network error";
                break;
            case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
                message = "Network timeout";
                break;
            case SpeechRecognizer.ERROR_NO_MATCH:
                message = "No match";
                break;
            case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
                message = "RecognitionService busy";
                break;
            case SpeechRecognizer.ERROR_SERVER:
                message = "error from server";
                break;
            case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
                message = "No speech input";
                break;
            default:
                message = "Didn't understand, please try again.";
                break;
        }
        return message;
    }

}
class Function {

    public static  boolean hasPermissions(Context context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        }
        return true;
    }
}

You can change the minimum time to listen by changing the below line

recognizerIntent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 5000);

 

23 Comments

  1. Tari Huxhold

    August 15, 2018 at 5:07 pm

    This website online can be a stroll-by for all the info you wanted about this and didn’t know who to ask. Glimpse here, and you’ll undoubtedly uncover it.

  2. click here

    August 16, 2018 at 11:29 am

    Excellent and good blog post is applied for all customers to collect the beautiful images and secured types of information also. relationship with country and issues are given supports for the readers. The different level of elections and good relationships talking with this post. The taking information is given real points for all. The supports and surprising supports and apprentice to be celebrity and given absolute matters are given for the readers.

  3. window

    August 17, 2018 at 8:06 am

    Wow ……………. THANKS FOR SHARING

  4. Nickolas Stoyer

    September 21, 2018 at 6:32 am

    Good web site you have got here.. It’s hard to find high-quality writinglike yours these days. I truly appreciate people like you!Take care!!

  5. furtdsolinopv

    October 7, 2018 at 5:44 am

    Glad to be one of the visitors on this awful site : D.

  6. Kraig Dearcos

    October 17, 2018 at 12:02 am

    Simply wanna input that you have a very decent web site, I love the pattern it really stands out.

  7. minecraft

    April 11, 2019 at 11:03 am

    Fabulous, what a web site it is! This webpage gives valuable information to us, keep it up.

  8. minecraft

    April 14, 2019 at 3:25 pm

    Hi there friends, fastidious post and good urging commented here, I am
    genuinely enjoying by these.

  9. minecraft

    April 16, 2019 at 5:50 am

    Thank you for some other informative site. The place
    else may just I get that kind of information written in such a perfect manner?
    I’ve a mission that I’m just now operating on, and I’ve been on the look out for such information.

  10. minecraft

    April 17, 2019 at 4:03 pm

    You need to be a part of a contest for one of the highest quality blogs on the internet.
    I’m going to recommend this blog!

  11. tinyurl.com

    April 19, 2019 at 10:09 pm

    Hi! This is my 1st comment here so I just wanted to give a quick shout out and say I
    genuinely enjoy reading your posts. Can you suggest any other blogs/websites/forums that go over the
    same topics? Thank you so much!

  12. minecraft

    April 21, 2019 at 7:13 am

    Good day very nice web site!! Man .. Excellent ..
    Amazing .. I’ll bookmark your blog and take the feeds also?
    I’m glad to seek out so many helpful information here within the submit, we want work out more techniques
    in this regard, thanks for sharing. . . . . .

  13. minecraft

    April 22, 2019 at 6:06 am

    I couldn’t resist commenting. Perfectly written!

  14. minecraft

    April 24, 2019 at 6:11 pm

    Hi! Do you use Twitter? I’d like to follow you if that would be
    okay. I’m undoubtedly enjoying your blog and look forward to new updates.

  15. Free Stuff

    May 1, 2019 at 8:16 am

    excellent points altogether, you just gained a brand new reader. What would you suggest in regards to your post that you made a few days ago? Any positive?

  16. boekhouding zzp

    May 6, 2019 at 6:39 am

    This blog was… how do I say it? Relevant!!
    Finally I have found something which helped me.
    Thank you!

  17. Ivelisse Stanfa

    May 12, 2019 at 7:43 am

    This blog was… how do you say it? Relevant!! Finally I have found something that helped me. Many thanks!|

  18. daemon tool

    May 17, 2019 at 8:44 pm

    I have figured out some important things through your blog post. One other subject I would like to talk about is that there are numerous games available and which are designed particularly for toddler age kids. They include things like pattern acceptance, colors, family pets, and designs. These commonly focus on familiarization in lieu of memorization. This makes little kids occupied without sensing like they are learning. Thanks

  19. Roger Jobs

    May 21, 2019 at 1:17 am

    Hi my loved one! I wish to say that this post is awesome, nice written and come with almost all vital infos. I’d like to see more posts like this .|

  20. how to get help in windows 10

    May 22, 2019 at 2:22 pm

    Right here is the perfect webpage for everyone who would like to find out about this topic.
    You realize so much its almost hard to argue with you (not that I
    actually will need to…HaHa). You certainly put
    a fresh spin on a topic that’s been written about
    for many years. Great stuff, just wonderful!

  21. nba 2k18 vc

    May 22, 2019 at 2:49 pm

    I appreciate, cause I found just what I was looking for. You’ve ended my four day long hunt! God Bless you man. Have a great day. Bye

  22. hill climb racing 2 app

    May 23, 2019 at 1:07 pm

    I have learned some significant things through your website post. One other point I would like to express is that there are lots of games out there designed in particular for preschool age children. They contain pattern acceptance, colors, dogs, and styles. These usually focus on familiarization rather than memorization. This will keep children and kids engaged without feeling like they are learning. Thanks

  23. gamefly free trial

    May 27, 2019 at 4:50 am

    My brother suggested I might like this website. He was entirely right.
    This post actually made my day. You cann’t imagine just
    how much time I had spent for this information! Thanks!

Leave a Reply