Android: Speech To Text using API

Android has a very cool feature that still many developers dont know. Apps like Any.DO uses speech to text conversion feature quite creatively. In today’s world of Siri, voice commands are of utmost importance. Android natively provides feature of Speech to Text so why not to use it in our app!

I will show you how to use Android’s Speech to Text API in an application.

Let’s make our demo application.

Demo App

The App will be very simple. It will have a button with Mic symbol. On click of which we trigger Android’s Speech to Text Intent which shows a dialog to take speech input. The speech input is then converted into text. The text is then displayed in a text view.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as SpeechToTextDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.speechtotextdemo.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. Just one Image Button to trigger Speech to Text API and one TextView to display result text that is converted from speech.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >

    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

The UI is very simply. One LinearLayout to organize the button and text view. Note the id for button: btnSpeak and text view: txtText which we will use in our Java code.

Step 3: Android Java Code to trigger Speech to Text API

Open SpeechToTextDemoActivity class and replace the code with following.

File: SpeechToTextDemoActivity.java

package net.viralpatel.android.speechtotextdemo;

import java.util.ArrayList;

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 {

	protected static final int RESULT_SPEECH = 1;

	private ImageButton btnSpeak;
	private TextView txtText;

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

		txtText = (TextView) findViewById(R.id.txtText);

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

		btnSpeak.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				Intent intent = new Intent(
						RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

				intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

				try {
					startActivityForResult(intent, RESULT_SPEECH);
					txtText.setText("");
				} catch (ActivityNotFoundException a) {
					Toast t = Toast.makeText(getApplicationContext(),
							"Opps! Your device doesn't support Speech to Text",
							Toast.LENGTH_SHORT);
					t.show();
				}
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

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

				ArrayList<String> text = data
						.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

				txtText.setText(text.get(0));
			}
			break;
		}

		}
	}
}

The heart of Speech to text Android API is package android.speech and specifically class android.speech.RecognizerIntent. Basically we trigger an Intent (android.speech.RecognizerIntent) which shows dialog box to recognize speech input. This Activity then converts the speech into text and send backs the result to our calling Activity. When we invoke android.speech.RecognizerIntent intent, we must use startActivityForResult() as we must listen back for result text.

Note how in above code we crate intent android.speech.RecognizerIntent and trigger it. Also we add one extra parameter using .putExtra() method. When invoking RecognizerIntent, we must provide extra RecognizerIntent.EXTRA_LANGUAGE_MODE. Here we are setting its value to en-US.

Since we triggered the RecognizerIntent via startActivityForResult(), we override method onActivityResult(int requestCode, int resultCode, Intent data) to handle the result data. The
RecognizerIntent will convert the speech input to text and send back the result as ArraList with key RecognizerIntent.EXTRA_RESULTS. Generally this list should be ordered in descending order of speech recognizer confidence. Only present when RESULT_OK is returned in an activity result. We just set the text that we got in result in text view txtText using txtText.setText().

One thing worth noting here is how to handle devices/android version that doesn’t support speech to text API. In such case, exception ActivityNotFoundException will be thrown when we try to start activity. In above example, we have catched this exception and displayed a message “Opps! Your device doesn’t support Speech to Text” using Toast.

Screen shots of Android App

And that’s all! Just execute the app in Android emulator or real device and see following output.

android-speech-to-text-api-demo

android-speech-to-text-activity

android-speech-to-text-conversion

android-speech-text

Download Source Code

Android_SpeechToTextDemo.zip (350 KB)

References

RecognizerIntent.html#ACTION_RECOGNIZE_SPEECH Documentation

Get our Articles via Email. Enter your email address.

You may also like...

126 Comments

  1. Shubhajit paul says:

    Excellent

  2. Priya says:

    Sir,This is actually good but i’m not getting text. after your third screen i’m getting “connection problem speak again”. I’m using Android 2.3

    • Sathishkumar says:

      @Priya: For solving Connection problem You have to connect internet…

      I have also got same problem.. After connect internet It works for me.. Try this…

    • samarth says:

      U’ll get the output on a Real device not on Emulator

  3. bryan says:

    Is it possible to simultaneously capture the audio to a file, so I would have the original audio and transcript? Or would I have to record to a file and transcribe the file somehow? Thanks!

  4. Brinda says:

    It gives me “Your device doesn’t support this program”
    Please help me what to do.I have downloaded the zip of this and I am not understanding what is the problem.I also created AVD with Audio recorder support but still it gives me the same problem.
    Please help me

  5. Suyog says:

    I have the same issue as Brinda. When I click on the button in the emulator I get the message: “Oops! Your device doesn’t support speech to text”

    I have already added audio recorder and audio playback to the emulator. What is the problem?

  6. rajesh says:

    @brinda , suyog , the speech does not work on emulator try on real device

  7. Gost says:

    hi ! great job man. i have a question. can i have the possibility to change the “en-US” to another one.

  8. Damodharan says:

    Really superb dude, It is working fine in my android HTC wildfire . Thanks

    • ana says:

      Its not working on emulator and giving error “Oops your device does not supplort speech to text”. How you run this code in htc wild Fire? plz guide me…

  9. Carroll Perkins says:

    I want to automatically text my voice replies while conversing on the phone. Is this possible and are there any apps?

  10. Lokesh says:

    shown Error as connection Problem..

  11. Rafael says:

    Unlike text to speech, speech to text must have an internet connection to provide the words spoken out. Text to speech do not need internet connection it uses the built-in android text to speech recognition (Pico TTS Engine) which you can find in settings under “Voice input and output settings”

  12. narendra says:

    Its working fine in my device by removing the android:showAsAction=”never” from the menu.activity_main. Can you please tell me what is the meaning of this and why we do required it in the application.

  13. Yash says:

    there is many errors…
    “unable to resolve target android-12”

  14. Yash says:

    r cannot be resolved to a variable in 12th line and 18th line but there are nothing….

  15. Jitendra Patel says:

    wow! it’s easy and amazing ….thanks sir….
    “txtText.setText(text.get(1));” insted of “txtText.setText(text.get(0)); ” for long speech.

  16. kuldeep says:

    i just wanted to know tht how could i listen to emails using text to speech engine provided by google i hv created an app which reads sms bt i also want it to read emails.send me appropriate code if possible.

  17. Rakesh says:

    Hello sir,
    the exception is occuring on mobile as well as emulator. ” “Opps! Your device doesn’t support Speech to Text””
    What should i do ?

  18. Steve says:

    Great article. Thanks. Worked it in to my app to save to database!

  19. Hisam says:

    is it possible to make it in an offline mode? tnx.

  20. Nikhil says:

    Hi,
    I want to change the dialog box of google mike icon when speech to text is on . I want to customize it the way I want . Is it possible bcoz there are apps on google play with speech to text in which the have used different mike icon e.g: of app is text by voice from google play.

  21. Eshrath says:

    displayed a message “Opps! Your device doesn’t support Speech to Text” . sir can you help me how to handle device in android..

  22. Surendra says:

    Great Article. Thanks. I just want to know one thing can we record our voice with this???

  23. shanawaz says:

    from where to download eclipse software…some1 give me the link for that

  24. Nagarjan says:

    Hai friends ! what is the procedure to change the lanugage????????

  25. Steve says:

    Hi, nice quickstart tutorial but I noticed one thing …

    you said:
    we must provide extra RecognizerIntent.EXTRA_LANGUAGE_MODE. Here we are setting its value to en-US.

    That’s not true, the possible values are
    LANGUAGE_MODEL_FREE_FORM and LANGUAGE_MODEL_WEB_SEARCH
    (http://developer.android.com/reference/android/speech/RecognizerIntent.html#EXTRA_LANGUAGE_MODEL)

    To specify a language (different from what is given by Locale.getDefault() ) for the recognition you have to add another extra:
    EXTRA_LANGUAGE with the code of the language you want to recognize
    eg. intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, new Locale(“de”, “DE”).toString());
    (http://developer.android.com/reference/android/speech/RecognizerIntent.html#EXTRA_LANGUAGE)

    best, Steve

  26. rishi says:

    I am getting an error while using it “can not be resolved …” at btn_speak pls help

  27. pranay says:

    thanx buddy

  28. Kulbhushan says:

    In this app when i stop speaking then it stops recognizing the voice is it any way to continue to recognize voice for some time and then stop the activity

    • Guy says:

      also wait for answer, same problem as this one

    • Sampada says:

      I’m also encountering this problem. Kindly help if you’ve found the solution. :)

  29. raj says:

    how to create one key on the keyboard for speach to text in android

  30. Alaa says:

    pleas how can I make speech to text program work continuously without click the button every time I want to speak ??

  31. Sohel says:

    Sir, i have found an error here:
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }

    here, menu cannot be resolved or it is not find view.
    How can i do now

    • Glen says:

      Try changing the line:

      getMenuInflater().inflate(R.menu.activity_main, menu); 

      to

      getMenuInflater().inflate(R.layout.activity_main, menu); 
      • mohammad says:

        does not worked

  32. pranjal says:

    if at run time it shows connection problem mean u have to add audio to your manifest file.

  33. jayesh says:

    dude i m using android 4.2.2 n it is saying that this device dosen’t support speech to text conversion……

  34. ajeeb says:

    hi..i got 2 errors here..

    txtText = (TextView) findViewById(R.id.txtText);

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

    why this 2 things got error..somebody plss help me…

  35. Udhay says:

    Nice dude!

  36. ashish says:

    Sir you post great tutorial about speech to text i am new in android i am not good programmer likee you.now i need your help please post very simple and clear example for ftp usage in Mu app thanks….

  37. Ashish says:

    How to use stack mob created API in our app.

  38. Ikbhal says:

    nice tutorial

  39. Lucas Borges says:

    Hi. U know if is possible add a button to START and another to STOP and only when press stop execute the process Voice to Text?

  40. devang says:

    device not found error,plz help me

  41. shilpi says:

    i’m geeting a popup saying ” unknown problem ” when i’m clicking on the speak button. what to do? .

  42. vmbharathi says:

    Excellent.!! This worked like a charm on my nexus 7 tablet!!
    Thanks a lot

  43. vishal says:

    Good Article…

  44. vishal says:

    superb app… thanks buddy..

  45. dotdot says:

    Please need help to run this on an emulator can u be kind enuf to run me through how to do this because I keep getting “Opps! Your device doesn’t support Speech to Text” please I need this very urgent. Please help .
    Thank you so much

  46. sara says:

    hi i have to do this project for that i have installed eclipse sdk is this enough or i need any audio playbacks plz help me

  47. littleN says:

    i’m getting error saying that ‘ Oops ! your device doesn’t support speech to text ‘
    Can you please help me..

  48. jtisaacs says:

    Great example code. It was simple and to the point. I had no problems with the code. Thanks so much!

  49. M_Yousif says:

    Hi

    Thank you for the source code, really helpful, however, it shows the Toast message “oops! your device doesn’t support speech to text” that I wrote, I don’t know where the problem is.

    please help me

  50. abhijit says:

    IF THE AUDIO FILE IS RECORDED THEN HOW TO CONVERT IT INTO TEXT.

  51. Sid says:

    This part is not right:
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, “en-US”);

    Should be:
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, “en-US”);

    thanks!

  52. Eman Hassan says:

    I am trying to change the language of the recognition from English to Arabic and I simply did this

    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, “ar-QA”); // Qatari Arabic

    But I get the text in English which is fine with me but interpreted wrong

    for example, I say “Yameen = right” >> I get the text as “Yeah mean” :)

    any suggestions on how I might be able to change the language of the recognition and the text?!

    another question, why do I have the button to activate the recognition, can’t I simply keep it listening the min I run the app?

    Thank you so much in advance for helping me understand :)

    • SARA says:

      use this

      Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
      
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
      intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ar-SA");
      
  53. Ajay Prasad says:

    Hi Viral Patel thanks for such a nice tutorial this program working perfect but i have some question regarding this post, this program recognize only alphabets not numeric or number if i say 100 it will print hundred, actually i want a result if i say 100 then it will show numeric value not a alphabets, can you help me out on this ?????

    • facing the same issue

    • krishna says:

      i am also facing the same problem. did u get any solution (or) work around for this ?

      • Anouar says:

        you guys got the rest as a text, so go ahead and parse the text and replace “hundred” by “100”. simple :)

        text.get(0).replace(“hundred”, “100”)

    • Anouar says:

      if you say “one hundred” it will display “100”. However, if you say “hundred” it will display “hundred”.

  54. pratap says:

    Hello viral patel,

    Thanks for sample application.

    It is working good. but in some devices it is working fine with out internet connection.
    but in some devices , it needs internet connection.

    Is there any other option to make speech to text in offline mode with out internet.

    Thanks,
    PRatap

  55. abhijit says:

    Is it possible to run the recognizer intent in the background and it is possible to convert a audio file to text by using this API in android.

  56. Yash Gupta says:

    Hey i want to know can i manually give input to the api . Like a recording to the api to convert it to text ??

  57. Krunal says:

    Hello,
    Great and easy example, can you please give me some suggestions my problem is i want to use the same functionality in a simple java class (non-activity class). how can i achieve this .?

  58. purushoth says:

    hi viral,i’m purushoth,i seen your project it’s fine k k ,i tried in my system this was not run properly if i click the button it’s record my speech it shows only the button(its first screen shot only displayed} help me…

  59. Rakesh says:

    What is the language tag for hindi-India?

  60. shabaz says:

    i download the source code and running it on sdk vertiual andriod device by it giving me error that (opp’s your device do not support speech to text ) what i have to do now

    • hector says:

      maybe you have to cut and paste!

    • Thuannguyen says:

      You must run the Android Project in real device (smartphone). It isn’t run in vitural device because vitural device not supported

  61. hector says:

    das ist bundaba!, excellent, muy bacano—- felicitaciones

    • Julian says:

      Es heißt wunderbar. Aber egal…

  62. Anil rai says:

    sir, this speech to text demo is not working in w-ifi.plz send me the code so it work in w-ifi.
    I am still waiting for your answer.

  63. HAR says:

    vertiual andriod device display an error …opp’s your device do not support speech to text …..any one can help me

    • Luckas says:

      Speech recognition is not supported by it, you have to test on some Android device with this functionality and this API.

  64. bery says:

    please,please who can answer my question:when i change the language of the recognition from English to Arabic i use(ar_SA) it is done but without any open,vibrio,Fracture and serenity on the arabic letters
    ,so what should i do to get the open,vibrio,Fracture and serenity on the arabic letters?
    Thank you so much in advance for helping me understand

  65. kalthum says:

    please help me soon:i want that when i read quran karim the program write it with full arabic language i mean with open,vibrio,Fracture , serenity and others on the arabic letters ,i change
    en-US to ar_SA its done but but without any open,vibrio,Fracture , serenity and others on the arabic letters ,so what should i do,please?or whats the type of english language that i can use to write every letter when i said in arabic language then it writes in english letter for example when i say “بِسْمِ الله” it will write “bismilah”.
    please,please answer me

  66. mark says:

    In my device, this application is not running without an Internet connection. What’s wrong?

  67. sangeeta says:

    hey can anybody mail me code for intenet class

  68. krishna kanth says:

    r.id cannot be resolved error plz help me guys..!!!

    • vinay says:

      Clean your project. If you still see the error then make sure you are importing the correct R class.
      android.R is the OS provided class while yourpackagename.R will be your class generated on build.

  69. getinet says:

    I want to change the language of the recognition from English to Amharic language.

    any suggestions on how I might be able to change the language of the recognition and the text?!

  70. stephen s d says:

    hello sir, i am doing a project on voice recognization i,e text to voice and voice to text, sir i got text to voice and i wrote the code for voice to text, but in emulator its coming that this device doesn’t support this application, so what to do sir please suggest me and also which supporting files and are needed to run this application, reply me as fast as possible sir please.

    • revan says:

      u should work with android 4.0
      below that it wont work…just try i had the same problem

  71. Pothiraj says:

    Nice coding.. 100 % working

  72. Es says:

    i want the opposite tts arabic – text arabic to speech – have you solution

  73. Luis says:

    Hi im having some problems , when im creating the layout this problem appear:
    @string/speak: No source found that matches the given name.

    • Jondy says:

      Go to your strings.xml and edit it by putting this:

      Speak

      and that should work.

  74. krishna says:

    this source code is very understandable.thank you

  75. Aravind says:

    hi,

    Can anybody confirm me that this code works in offline mode…. for me its working fine in online but when iam trying in offline mode.. it does’t work….. when i went through the code there is no option indicating that internet is required?… so i think this should work in offline….pls suggest ….
    any references which work in offline….

    Thanks
    Aravind

  76. Izy says:

    Hello sir
    thanks for the tutorial…I encounter a problem where when I speak to the device then it load of something..after that the textview area doesn’t show up..any idea why??
    im using samsung galaxy mini
    looking forward for your respond..thank you :)

  77. shruthi says:

    THank u

  78. sumit yadav says:

    Thanks Viral. Its Nice Tutorial. It works perfectly on real android device. Good Luck.

  79. Anthony says:

    Will Android Speech take pre-recorded audio?

  80. praveen says:

    i want speech to text conversion in java please help me

  81. praveen says:

    how do i change my pacakage name…..net.viralpatel.android.speechtotextdemo

  82. madhu says:

    thanq …u helped me

  83. Ravi Teja M says:

    While i m trying this app in emulator it is showing the toast message “your device doesn’t support speech to text”. May i know the reason?

  84. Dhruvika says:

    hello sir
    i am Dhruvika.i am mca final year student.in 5 th sem dessertation subject .my dessertation defination is speech to text in gujarti for android mobile.i have no idea how to add gujrati voice typing languge in mobile.

  85. pratik says:

    IT GIVES NO MATCHES FOUND DIALOG……CAN ANYONE TELL ME WHY?

  86. Kasalwe says:

    Perfect. Tried it on my Note 3 and it is just perfect, and simple. Thanks

  87. abhishek says:

    android:src=”@android:drawable/ic_btn_speak_now”…….THIS LINE IS SHOW THE FOLLOWING ERROR IN ECLIPSE…..”@android:drawable/ic_btn_speak_now requires API level 3 (current min is 1)”…..HELP OUT ASAP

  88. Glauber says:

    Cara muito bom, simples e ótimo exemplo!!!!

  89. dan rabino says:

    Hello sir,

    How do you use Natural languange Processing in this program. thank you. urgent badly needed.

  90. vijaya says:

    Hello sir
    I am beginner of android.I have one doubt my application contain Telugu song lyrics files are stored in res/xml/abc,xml like this how to read the files when i reading it display like boxes how to read Telugu in my application and also how to place xml folder in array list folder contain 777 files song lyrics how to read it please help me.

  91. CHUN LI says:

    hey can i convert the speech from english to text in another language,,,,what changings do i ahve to made,,,,PLZ REPLY….

  92. Shobin says:

    My app does not open it opens some other app.please help me…

  93. Shobin says:

    Is it requires internet?

    • yes, but if you download that language library then it will also work offline.

  94. kanagalingam says:

    hi guys,
    i just want to save the speech recognition o/p (i.e., text) in a separate text file like notepad.. How can i do it??? Any suggestions would be greatly appreciated!!!

  95. Fika says:

    I try it in my smartphone, not virtual. But also show ‘your device doesn’t support speech to text’, please help me

  96. Jondy says:

    The code works fine when I run it on Android Studio, but when I run it on my device it says that app has stopped working. It seems that there is a bug which blocks the app from working fine on my phone. Can someone help me with that problem?

  97. Mahtab Karim says:

    you make my day… i was need of this in my map based application …. works fine….. Thanks ViralPatel

  98. revan says:

    hi…can anybody suggest me how to remove the google logo from it:)

  99. Mangesh Panchwagh says:

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

  100. tharun says:

    Error:(17, 37) No resource found that matches the given name (at ‘contentDescription’ with value ‘@string/speak’). How to solve this?

  101. Keshav Kartik Vaishnav says:

    Sir I want To save this text file ????

  102. Keshav Kartik Vaishnav says:

    Sir I want To save this text file ????

  103. Manjusha says:

    Thanks you…
    It work for me.
    but can we done it without internet??because when internet is off it gives error.
    so is there any solution for this

  104. Saurabh Rathod says:

    PLEASE provide speech to text in swing or simple code……

Leave a Reply

Your email address will not be published. Required fields are marked *