Android comes with an inbuilt feature speech to text through which you can provide speech input to your app. With this you can add some of the cool features to your app like adding voice navigation(Helpful when you are targeting disabled people), filling a form with voice input etc.,

In the background how voice input works is, the speech input will be streamed to a server, on the server voice will be converted to text and finally text will be sent back to our app.

If you want to do the other way i.e converting text to speech, follow my previous tutorial Android Text to Speech

speech to text banner

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.

android speech to text

So let’s start by creating simple app.

Sample Application

1. Create a new project in Eclipse by going to File ⇒ New ⇒ Android Application Project and give required information.

2. Open strings.xml located under res ⇒ values and add below string values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Speech To Text</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="speech_prompt">Say something&#8230;</string>
    <string name="speech_not_supported">Sorry! Your device doesn\'t support speech input</string>
    <string name="tap_on_mic">Tap on mic to speak</string>
</resources>

3. Open colors.xml located under res ⇒ values and add below colors. If you don’t see colors.xml, create a new file and add the values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="white">#ffffff</color>
    <color name="bg_gradient_start">#31244e</color>
    <color name="bg_gradient_end">#6b394c</color>
</resources>

4. Now open the layout file for main activity(activity_main.xml) and add below code to create a simple layout.

<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:background="@drawable/bg_gradient"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtSpeechInput"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="100dp"
        android:textColor="@color/white"
        android:textSize="26dp"
        android:textStyle="normal" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="60dp"
        android:gravity="center"
        android:orientation="vertical" >

        <ImageButton
            android:id="@+id/btnSpeak"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@null"
            android:src="@drawable/ico_mic" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="@string/tap_on_mic"
            android:textColor="@color/white"
            android:textSize="15dp"
            android:textStyle="normal" />
    </LinearLayout>

</RelativeLayout>

5. Finally open your MainActivity.java and do the following changes. In simple adding speech input will be done in two steps.

Step 1: Starting RecognizerIntent
First we need to create a RecognizerIntent by setting necessary flags such as
ACTION_RECOGNIZE_SPEECH – Simply takes user’s speech input and returns it to same activity
LANGUAGE_MODEL_FREE_FORM – Considers input in free form English
EXTRA_PROMPT – Text prompt to show to the user when asking them to speak

Step 2: Receiving the speech response
Once the speech input is done we have to catch the response in onActivityResult and take appropriate action needed.

package info.androidhive.speechtotext;

import java.util.ArrayList;
import java.util.Locale;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private TextView txtSpeechInput;
	private ImageButton btnSpeak;
	private final int REQ_CODE_SPEECH_INPUT = 100;

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

		txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
		btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);

		// hide the action bar
		getActionBar().hide();

		btnSpeak.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				promptSpeechInput();
			}
		});

	}

	/**
	 * Showing google speech input dialog
	 * */
	private void promptSpeechInput() {
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
				RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
				getString(R.string.speech_prompt));
		try {
			startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
		} catch (ActivityNotFoundException a) {
			Toast.makeText(getApplicationContext(),
					getString(R.string.speech_not_supported),
					Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * Receiving speech input
	 * */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		switch (requestCode) {
		case REQ_CODE_SPEECH_INPUT: {
			if (resultCode == RESULT_OK && null != data) {

				ArrayList<String> result = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
				txtSpeechInput.setText(result.get(0));
			}
			break;
		}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

Run the app in a real device. Make sure that the device has good internet connectivity while you are testing.

Enabling Offline Mode

Right now all the devices are not supporting offline speech input. However you can follow this discussion to enable offline speech input for supported devices.

I have downloaded speech input packages on my Nexus 5 and offline speech is working fine.

1. On your device go to Settings -> Language and Input. Click on icon on Google voice input.
2. Under ALL tab select the language you want to download.
3. Once the language package downloaded, you can see it under INSTALLED tab.

android speech to text offline mode
android speech to text offline mode
android speech to text offline mode
Subscribe
Notify of
guest
232 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Abhishek
Abhishek
6 years ago

Nice one Ravi

Dinesh
Dinesh
6 years ago

Nice Post 🙂

pawan
pawan
6 years ago

Thumbs up 🙂
Please provide a tutorial for Sending a list of contacts (phone and sim) to server and how to receive the same from server

Ravi Tamada
6 years ago
Reply to  pawan

Hi Pawan,

Thanks for the suggestion. I’ll try to write it on next week. Uploading them to a server is different topic though, I can explain reading part from SIM/Phone.

Pawan
Pawan
6 years ago
Reply to  Ravi Tamada

Thank you Ravi.
I’ve done an application for displaying a list of contacts but i’m unable to upload and download the list of contacts to and from server respectively. It will be helpful for me if you provide a tutorial for the same. Waiting for the coming week . Thanks in advance

Alpesh Nd
6 years ago

Ravi sir, Is there any way to change Google’s stock voice recognition UI ??

Ravi Tamada
6 years ago
Reply to  Alpesh Nd

RecognitionListener provides a way to implement custom UI.
http://stackoverflow.com/questions/23091584/android-custom-voice-recognition-gui-dialog

LouisG
LouisG
6 years ago

Can i see your bg_gradient.xml file, i don’t really understand how write it..

Ravi Tamada
6 years ago
Reply to  LouisG

Oops! I missed it. I’ll update the article.

Here is the code for gradient bg

Aveena
Aveena
5 years ago
Reply to  Ravi Tamada

i want ico_mic.xml please

Fattur
Fattur
5 years ago
Reply to  Aveena

change it with
@android:drawable/ic_btn_speak_now
And it works dude

tEi
tEi
6 years ago

Looks awesome, gonna try it. Many thanks (=

Ravi Tamada
6 years ago
Reply to  tEi

You are welcome 🙂

Rebecca Wu
Rebecca Wu
6 years ago

Sponsored Review Inquiry

Hi,

This is Bennie from EaseUS Software Company, a leading software
provider for data backup and recovery.

We’re recently looking for sponsored reviews. And it occurred to me
that you might be interested in.

You can keep your authentic thoughts in the review.

How do you quote for writing one review with two links?

Giveaway is also available to us if you’re interested in.

Please contact bennie@easeus.com if you have any suggestions for cooperation.


Best regards
Bennie
Chengdu Yiwo Tech Co., Ltd.
http://www.easeus.com
http://www.partition-tool.com
http://www.todo-backup.com

Ravi Tamada
6 years ago
Reply to  Rebecca Wu

Hi Rebecca,

Please mail me at ravi8x@gmail.com

Thank You

Dr. Atul Tiwari
6 years ago

Hi, thanks for your tutorials. From NO-programmer to a beginner, a huge credit goes to your tutorials (actually just after Google and Stackoverflow).
Sorry for being off-topic, but I am looking for Pagination of TextView for Android (something like e-book reader). Just wanted to know, if you have made any tutorial/demo of that? All the available demo like pageturner etc. are way too complex for me to understand.
Or, if you can point me to any other site from where I can get the basic idea for making it?
(will wait for your reply)
Thanks.
Regards,
Dr. Atul Tiwari

guy
guy
6 years ago

i did not understand this step

ACTION_RECOGNIZE_SPEECH – Simply takes user’s speech input and returns it to same activity
LANGUAGE_MODEL_FREE_FORM – Considers input in free form English
EXTRA_PROMPT – Text prompt to show to the user when asking them to speak

from where i got those .??

ali
ali
6 years ago
Reply to  guy

i want ico_mic.xml please

Fattur
Fattur
5 years ago
Reply to  ali

change it with
@android:drawable/ic_btn_speak_now
And it works

hafoosa
hafoosa
6 years ago
Reply to  guy

from code …
it is there in code

hafoosa
hafoosa
6 years ago

i do all steps but not work … what is wrong ???

it say >Sorry! Your device doesn’t support speech input

Manraj
Manraj
5 years ago
Reply to  hafoosa

There is no problem at all with the app that you created with Eclipse but the problem is that your phone doesn’t support Voice Recognition.Try getting a new phone that supports Voice Recognition and then try to compile and run the app on the device or maybe run the app on Eclipse.But if you would want to run the app on Eclipse,you would require a powerful PC or Laptop as the Android SDK downloaded needs a powerful PC.

Hope this helps you.
-Manraj

Waseem
Waseem
6 years ago

How to implement pdf to speak in android

Tirsa Aprillia
Tirsa Aprillia
6 years ago

I need help you and I have sent it to you. Thanks before

Tirsa Aprillia
Tirsa Aprillia
6 years ago

How to make a speech recognition with function start and stop to speak. Please help me, I need the code

fuck me too
fuck me too
6 years ago

Is internet permission not required?

fuck me too
fuck me too
6 years ago

Excellent Tutorial! You rock dude/

Aryan
Aryan
6 years ago

What can I put in place of LANGUAGE_MODEL_FREE_FORM to change the language of input. Can it be auto recognized?

webdevlamp
webdevlamp
6 years ago

very nice post

Mayur
Mayur
6 years ago

How can i convert japanese into Text. I tried saying few japanese sentences but unable to get it in japanese text. I even downloaded the japanese language pack in phone. Please help me.

KASMIN
KASMIN
6 years ago

hello sir thanks for helping.
im new in android development im trying to make an app which listen our voice n make to text of it ..
here i wann know how to make “append code” to acccept full speech and give it as notes..
thank you

KASMIN
KASMIN
6 years ago
Reply to  KASMIN

thanks. i got solution
i used : tv.append(getResult());

chlong chlong
chlong chlong
5 years ago

Hi, How I could implement this to your tab fragment? anyhelp would do…

Rahul
Rahul
5 years ago

Hi Ravi In this application process speech online why network permission is not unabled in manifest file

Sitters
Sitters
5 years ago

How can I add a confirmation before? such as Did you say “Hello World” (yes or no)?

Ena
Ena
5 years ago

hello, how do you destroy it? i mean, i think it’ll have an error that services are leaking or something? i haven’t seen you closing it in onDestroy

shobin kumar
shobin kumar
5 years ago

Hello Ravi,I want to know that it requires internet connection??? I want to do this without internet conmnection..Please help

Marcos Willians
Marcos Willians
5 years ago
Reply to  shobin kumar

This code does not worked for me too…

I guess that this is one more fake “Now voice recognition offline in Android!”

The offline recognition worked for me in other app like “notepad” but dont work with this code. Online works, offline no, sad but true.

Fattur
Fattur
5 years ago

Hi, Thanks for great guide. But there are some things. First Download Code button doesn’t works. Secondly it gives an error at
android:src=”@drawable/ico_mic”
So I think we need ico_mic.xml. But I couldn’t find it in your codes. If you share it I would be gladly appreciated. Thanks a lot

Fattur
Fattur
5 years ago
Reply to  Fattur

Oh, NVM for the Second one. But it should have changed with
@android:drawable/ic_btn_speak_now
Thank’s

Mahtab Karim
4 years ago
Reply to  Fattur

you can just replace it with your ICON… just write
@drawable/icon_image1 instead of @drawable/ico_mic

Sukamal Das
Sukamal Das
5 years ago

hey this is great thanks…can u tell me how to get this voice file

santosh keshari
santosh keshari
5 years ago

Hi Ravi, google voice recognition engine does not recognize medical terms. I need to implement app to detect medical terms. Which engine shall i use? Do you have any ides?

Yoshua Rudy
Yoshua Rudy
5 years ago

Hi, Ravi I already press the subscribe button but I didn’t receive any email regarding confirmation of my subscribtion

Laércio Metzner
Laércio Metzner
4 years ago

You did a great Job! I’m looking for some how to get just Letters and Numbers, not full words nor sentences. My users are going to enter information just like ‘AA001’, ‘BC022’, ‘AD011’, and I still had not figure out how to get it.

karuna thevar
karuna thevar
4 years ago

” your device doesnt support speech to text “, I am getting this error

Gnana poobalan
Gnana poobalan
4 years ago

Does it work on Android 5 with offline mode in micromax android one device?. I need to know about it. Any Suggestions would be appreciated..

Thanks in advance,
-poobalan

azad
azad
4 years ago

i want create apk speech to text can you help me
?

Mirko Pontoriero
Mirko Pontoriero
4 years ago

Hi, I would like to know why this App not work offline? I have a NEXUS 5 and I following the code also the screenshot example but not work. I hope that someone answer me early. Thanks

Ravi Tamada
4 years ago

Speech to Text needs internet. When we give speech to app, it connect to google services and translates audio to text.

Nikhil
Nikhil
4 years ago

Hi Ravi, I tried implementing offline support as you have indicated. I downloaded the packages, but still offline support is not working for my app. The app works perfectly when its online…. Any suggestions?

Mangesh Panchwagh
Mangesh Panchwagh
4 years ago

hey
I have a question When spoken words are converted into text, how to store it
into a text file. So that I can use it(text file) later.

Rohit Kumar
Rohit Kumar
4 years ago

Hi Mangesh,
I’ve not tried it myself but I’m pretty sure this would work. Get the text from the textView and save it in a file. http://developer.android.com/training/basics/data-storage/files.html

Arifin Firdaus
Arifin Firdaus
4 years ago

Hi Ravi, How can I input voice with another language other than english? Can anyone tell me???

Arifin Firdaus
Arifin Firdaus
4 years ago
Reply to  Arifin Firdaus

i found it (change the primary input voice) in settings -> Language & input -> Voice input(under the speech section).

brahmy
brahmy
4 years ago

voice search miss understanding problem i am facing sir.suppose if i wana speaking R then it is understanding like “are” and then it’s displaying like this..how resolve this problem.

Adam
Adam
4 years ago

thank you Mr. Ravi Tamada for this tutorial. it’s helpful code,

I have one question: how I can start voice recognition directly when button clicked (without using Intent).
do you have any Idea how I can do this?

thanks

shivam
shivam
4 years ago

hi Ravi i need your help in developing some android apps i want to interconnect two apps for sharing some details or data using mobile network not in WiFi or Bluetooth but i can’t understand how to implement can you help me for implementation………….

Ravi Tamada
4 years ago
Reply to  shivam

Are the two apps installed on same device?

Lonr
Lonr
4 years ago

Question: How can i implement voice trigger input just like, “ok google” in Android’s google app?

Антон Рудько
Антон Рудько
4 years ago
Reply to  Lonr

start function promptSpeechInput() in onCreate without onClick and wait answer “ok google” only before find another text… sorry me English)))

Wiam
Wiam
4 years ago

It’s awesome. Thanks a lot

Sokhorn Houn
4 years ago

how can I get recorded voice and text at the same time?

Suvojit
Suvojit
4 years ago

Hi, can we convert the audio from a video and convert it to text using Speech to Text API in Android ?

Adjei Bernice
Adjei Bernice
4 years ago

I am have been able to develop an e-voting android application but my supervisor wants me to add automatic speech recognition feature. I have no idea where to start. Should i create a new class for the ASR and call the methods in the OnCreate() or what should i do. Please help

Hitesh Kumar Sahu
Hitesh Kumar Sahu
4 years ago

If you dont want to show annoying prompt dialog then you can look into my repo.https://github.com/hiteshsahu/Android-TTS-STT . I tried to store my learing in that POC

BuddySteve
BuddySteve
4 years ago

Can you at least spell correctly so we don’t have to try and figure out what you’re saying?

Shubham Kulkarni
Shubham Kulkarni
4 years ago

I got your whole code but I m not geting that which api u used for conversion of speech to text in thr????

nafees ahmed
nafees ahmed
4 years ago

there is no api used

Shubham Kulkarni
Shubham Kulkarni
4 years ago
Reply to  nafees ahmed

Sir can u plz explain what is recognizer intent????

Shubham Kulkarni
Shubham Kulkarni
4 years ago

Coz I want to build a android app for deaf people, and I don’t want to use any avlbl api

vikash kumar
vikash kumar
4 years ago

How can I use different different icon for different purposes.Like one icon on tap gives information about the nearby malls .

Shubham Kulkarni
Shubham Kulkarni
4 years ago

while executing the code I m having “Rendering Problems Exception raised during rendering: com/android/util/PropertiesMap” what should I do??

Arun Kumar
Arun Kumar
4 years ago

hai ravi
impressive projects. wish your work should continue for long time.
i design a project in which user could feed the column values using
voice. for example i have 4 edittext in which i should get the values using
speaktotext methode.and send the same to php,mysql server.
how can i get separate speaktotext in each edittext when it got focus.
current speech converted to text in the edittext

Olive Paul
Olive Paul
4 years ago

Hi Ravi,
Rajesh bhaiya is my friend. I hope u r fine. I’m too an Sr Android Application Dev…….Update your article on evry wk…… 🙂

232
0
Would love your thoughts, please comment.x
()
x