RSS

Android Tutorials << Building a Language Translator App with Text To Speech feature

05 Feb

One of my friends is going abroad – to Germany. I thought I’d make her an app that would let her enter what she wants to say in English translate it to German then speak it out.

Here goes:
I am going to be using the Bing Translate API – really cool coz they give u like two million queries, that’s a lot (unfortunately Google translate API isnt free).
First, download this java library. Place this in your libs folder.

We need the Client Id and Client username from the Microsoft MarkerPlace. Here are the instructions on how to get this.
 

I am gonna build this:
Screenshot_2013-02-05-15-07-38

activity_main.xml

<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" >

    <EditText
        android:id="@+id/etUserText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="31dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/tvTranslatedText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etUserText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="168dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/bTranslate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/etUserText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Translate" />

    <Button
        android:id="@+id/bSpeak"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tvTranslatedText"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="46dp"
        android:text="Speak" />

</RelativeLayout>

To get translated text do this:

public String translate(String text) throws Exception{
	// Set the Client ID / Client Secret once per JVM. It is set statically and applies to all services
       Translate.setClientId("CLIENT USERNAME");
       Translate.setClientSecret("CLIENT SECRET");
       
       String translatedText = "";
       
       // English AUTO_DETECT -> gERMAN Change this if u wanna other languages
       translatedText = Translate.execute(text,Language.GERMAN);
       return translatedText;
   }

The Text-To-Speech bit:

public class MainActivity extends Activity implements OnInitListener {

	private TextToSpeech tts;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tts = new TextToSpeech(this, this);
        speakOut("Ich"); //This is how you will get the phone to  speak    
}

@Override
public void onInit(int status) {
	// TODO Auto-generated method stub
	if (status == TextToSpeech.SUCCESS) {
		 
        int result = tts.setLanguage(Locale.GERMAN);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
            
            //speakOut("Ich");
        }

    } else {
        Log.e("TTS", "Initilization Failed!");
    }
}
   
private void speakOut(String text) {
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}

And the complete code:

package com.gilo.translatr;

import java.util.Locale;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

public class MainActivity extends Activity implements OnInitListener {

	private TextToSpeech tts;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        tts = new TextToSpeech(this, this);
        ((Button) findViewById(R.id.bSpeak)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				speakOut(((TextView) findViewById(R.id.tvTranslatedText)).getText().toString());
			}
		});
        
        ((Button) findViewById(R.id.bTranslate)).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				
				
				class bgStuff extends AsyncTask<Void, Void, Void>{
					
					String translatedText = "";
					@Override
					protected Void doInBackground(Void... params) {
						// TODO Auto-generated method stub
						try {
							String text = ((EditText) findViewById(R.id.etUserText)).getText().toString();
							translatedText = translate(text);
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							translatedText = e.toString();
						}
						
						return null;
					}

					@Override
					protected void onPostExecute(Void result) {
						// TODO Auto-generated method stub
						((TextView) findViewById(R.id.tvTranslatedText)).setText(translatedText);
						super.onPostExecute(result);
					}
					
				}
				
				new bgStuff().execute();
			}
		});
    }

   public String translate(String text) throws Exception{
	  
	   
	// Set the Client ID / Client Secret once per JVM. It is set statically and applies to all services
       Translate.setClientId("CLIENT ID"); //Change this
       Translate.setClientSecret("CLIENT SECRET"); //change
       
       
       String translatedText = "";
       
       translatedText = Translate.execute(text,Language.GERMAN);
	   
       return translatedText;
   }

@Override
public void onInit(int status) {
	// TODO Auto-generated method stub
	if (status == TextToSpeech.SUCCESS) {
		 
        int result = tts.setLanguage(Locale.GERMAN);

        if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("TTS", "This Language is not supported");
        } else {
            
            //speakOut("Ich");
        }

    } else {
        Log.e("TTS", "Initilization Failed!");
    }
}
   
private void speakOut(String text) {
    tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
   
}

There is a lot you can do, but I am feeling to lazy. Hope you learnt something.

[UPDATE] Check out the App here, I just gave it a better look but its still more or less the same thing described above.
 

Advertisements
 
58 Comments

Posted by on February 5, 2013 in Uncategorized

 

58 responses to “Android Tutorials << Building a Language Translator App with Text To Speech feature

  1. JrHenry

    April 4, 2013 at 11:59 am

    thank you for this wonderful app..but i wonder only german language works..i manage to translate it to chinese but when i press the speak button, the app doesnt read it..

     
  2. Gilbert Kimutai

    April 4, 2013 at 12:49 pm

    I also had that problem. One of the solutions that I had in mind is to download the sound file from bing and then play it. It still gave me some problems too. Let me look at it again then get back to you.

     
  3. Sodein Graham-Douglas

    May 4, 2013 at 10:21 am

    Sorry, But which of the libs are you meant to copy the Bing translator file into?

     
  4. Sodein Graham-Douglas

    May 6, 2013 at 4:24 pm

    I’m still getting errors as i click on the translate button regardless of me downloading the required file needed to translate the input string. Help?

     
    • Gilbert Kimutai

      May 9, 2013 at 2:29 am

      What do the errors say?

       
  5. factor

    May 9, 2013 at 2:55 am

    what there download file? please ?

     
  6. Gilbert Kimutai

    May 9, 2013 at 3:11 am

    Here is the project to this app. https://dl.dropboxusercontent.com/u/91662709/Translatr.zip . Unzip to your local drive. Then in eclipse, go to File->Import choose android->Existing android code to workspace. Then browse to the translatr folder. After it gets to your workspace, open the Translatr.java and change this

    Translate.setClientId("USER NAME GOES HERE");//CHANGE THIS
    	       Translate.setClientSecret("CLIENT SECRET"); //CHANGE THIS
    

    the username and client secret you got from Microsoft bing translater site. Tell me if you get any more problems.

     
    • factorchrist

      May 9, 2013 at 4:28 am

      thanks

       
    • clyde

      November 30, 2013 at 3:54 am

      hello, i tried to download the project and change the id and secret I got from the Microsoft bing translator..My problem is that when I try to run it, it suddenly stopped.. “Unfortunately, Translatr has stopped” please help me

       
      • Gilbert Kimutai

        November 30, 2013 at 4:11 am

        check the logs for the exception

         
      • clyde

        November 30, 2013 at 4:16 am

        these are the errors:

        11-30 04:07:46.701: E/AndroidRuntime(1170): FATAL EXCEPTION: main
        11-30 04:07:46.701: E/AndroidRuntime(1170): java.lang.VerifyError: com/gilo/translatr/Translatr
        11-30 04:07:46.701: E/AndroidRuntime(1170): at java.lang.Class.newInstanceImpl(Native Method)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at java.lang.Class.newInstance(Class.java:1130)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.ActivityThread.access$600(ActivityThread.java:141)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:99)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
        11-30 04:07:46.701: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)

        i hope it could be fix 😦

         
  7. Manoj

    May 21, 2013 at 11:20 am

    05-21 16:43:15.955: E/AndroidRuntime(1204): FATAL EXCEPTION: AsyncTask #1
    05-21 16:43:15.955: E/AndroidRuntime(1204): java.lang.RuntimeException: An error occured while executing doInBackground()
    05-21 16:43:15.955: E/AndroidRuntime(1204): at android.os.AsyncTask$3.done(AsyncTask.java:299)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.lang.Thread.run(Thread.java:856)
    05-21 16:43:15.955: E/AndroidRuntime(1204): Caused by: java.lang.NoClassDefFoundError: com.memetix.mst.translate.Translate
    05-21 16:43:15.955: E/AndroidRuntime(1204): at com.example.demogoogletranslation.MainActivity.translate(MainActivity.java:86)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at com.example.demogoogletranslation.MainActivity$2$1bgStuff.doInBackground(MainActivity.java:58)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at com.example.demogoogletranslation.MainActivity$2$1bgStuff.doInBackground(MainActivity.java:1)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at android.os.AsyncTask$2.call(AsyncTask.java:287)
    05-21 16:43:15.955: E/AndroidRuntime(1204): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
    05-21 16:43:15.955: E/AndroidRuntime(1204): … 5 more

     
    • Ajay Shrestha

      June 24, 2013 at 8:55 pm

      Same problem..please help me

       
  8. monigarr

    May 29, 2013 at 7:03 pm

    Thanks for sharing this tutorial, it was fun to build.

     
  9. Buppy

    June 19, 2013 at 11:04 am

    when i write something in German it shows unable to translate.what is the problem .can any one help ?

     
  10. Rajith Sam

    July 23, 2013 at 3:35 pm

    Hi..! am gonna trying to built android application for translating caller language to the listener language. I need your idea and help.

     
    • Gilbert Kimutai

      August 9, 2013 at 5:03 am

      Thats an amazing idea. Just the other day I heard google announce they are going to do that too. Anyway you can have a look at android Voice recognition. I’ll maybe post code snippet for that. The other bit is the Text-to-Voice which is already done above.

       
    • Gilbert Kimutai

      August 9, 2013 at 5:53 am

       
  11. Farrakh Javed - Software Developer

    August 15, 2013 at 9:55 am

    I am getting eror of no class found…Kindly help

     
    • Gilbert Kimutai

      August 15, 2013 at 2:12 pm

      check that you have added the jar file to the lib folder.

       
  12. Atul Vishwakarma

    August 23, 2013 at 5:36 am

    really nice……!!!! its great to have people like you on Web who are so humble that they share there hard work on an open source..!! keep this good work going !!

     
  13. Atul Vishwakarma

    August 23, 2013 at 8:21 am

    i am running this app on my samsung galaxy s2 and when i type any sentence in english and try to convert it any other language, it is giving the message “unable to translate” ………!! 😦

     
  14. Atul Vishwakarma

    August 23, 2013 at 9:00 am

    error removed…..working great !!!! 🙂

     
    • ian

      September 10, 2013 at 8:35 am

      what did u do ? could u share please ?

       
  15. ian

    September 10, 2013 at 8:34 am

    i’m always get.. unable to translate.. 😦
    even i had input my client id and the secret password 😦

     
    • Gilbert Kimutai

      September 10, 2013 at 8:42 am

      It could b something small, this the project I use https://dl.dropboxusercontent.com/u/91662709/Translatr.zip . Change the client_id and secret to your own.

       
      • ian

        September 10, 2013 at 9:21 am

        downloading now…
        btw thx for replying..

        just curious when doing Translate.execute : this problem show .. error retrieving translation message: Null

        any idea ?

         
    • Gilbert Kimutai

      September 10, 2013 at 9:27 am

      Maybe it could be that the device is unable to access Internet.

       
  16. mahmoud

    October 6, 2013 at 4:08 pm

    hi !!
    Thanks for sharing this tutorial..
    but I have probleme ….I changed the Client ID and the Client Secret but when i tried to use the translator api in my android application i am getting the following error:
    java.lang.Exception: [microsoft-translator-api] Error retrieving translation : Not trusted server certificate
    Please provide some leads to solve this issue.

    Best regards,

     
    • Gilbert Kimutai

      October 17, 2013 at 6:09 am

      Are you running this on an emulator? That error means that your android device is missing some certificate that microsoft needs.

       
  17. Louise

    October 12, 2013 at 9:48 am

    why does it force close
    when i pressed the button translate

     
    • Gilbert Kimutai

      October 17, 2013 at 6:02 am

      Please check with the logs during runtime. If you downloaded my project it should run fine. Build your code from the project Ive provided if you are having alot of trouble.

       
  18. santosh

    October 17, 2013 at 5:41 am

    In client_id and secret what we should keep im new to android please help me.. SHould we connect this to db?

     
    • Gilbert Kimutai

      October 17, 2013 at 6:01 am

      There is a link in the tutorial detailing how to get the client id and secret from the microsoft azure store. You do not need a db. Unless u want to add some extra feature.

       
  19. santosh

    October 18, 2013 at 6:47 am

    In microsof site im getting error like this…

    Method: Speak()

    Parameter:

    Message: The incoming token has expired. Get a new access token from the Authorization Server.
    message id=wd2.V2_Rest.Speak.83479235092

     
  20. santosh

    October 18, 2013 at 6:48 am

    if we can keep id and secret by our own hw can we keeep and what ..?

    please help me thank you..!

     
  21. santosh

    October 18, 2013 at 6:59 am

    i can see id in dat site.. what about secret where we get that… please help me out..

     
  22. clyde

    November 30, 2013 at 7:53 am

    please help me.. whenever I press the Translate Button it force close…
    Please help me..

    the error in Log are:

    11-30 07:51:14.419: E/AndroidRuntime(2193): FATAL EXCEPTION: AsyncTask #4
    11-30 07:51:14.419: E/AndroidRuntime(2193): java.lang.RuntimeException: An error occured while executing doInBackground()
    11-30 07:51:14.419: E/AndroidRuntime(2193): at android.os.AsyncTask$3.done(AsyncTask.java:299)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.lang.Thread.run(Thread.java:841)
    11-30 07:51:14.419: E/AndroidRuntime(2193): Caused by: java.lang.NoClassDefFoundError: com.memetix.mst.translate.Translate
    11-30 07:51:14.419: E/AndroidRuntime(2193): at com.example.bing.MainActivity.translate(MainActivity.java:84)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at com.example.bing.MainActivity$2$1bgStuff.doInBackground(MainActivity.java:56)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at com.example.bing.MainActivity$2$1bgStuff.doInBackground(MainActivity.java:1)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at android.os.AsyncTask$2.call(AsyncTask.java:287)
    11-30 07:51:14.419: E/AndroidRuntime(2193): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
    11-30 07:51:14.419: E/AndroidRuntime(2193): … 4 more

     
  23. kals

    January 13, 2014 at 9:56 am

    Hello your project is working properly but there is one problem that it is not converting English to Hindi only. so plz give me solution as soon as possible. It’s Urgent really

     
  24. Gchoco

    January 20, 2014 at 4:29 pm

    how to translate another language to English

    pls help me

     
  25. Guila

    March 10, 2014 at 1:21 pm

    hi, i’d like to ask, can this be used on text to text translation too? 🙂 Thanks!

     
  26. Nguyen Ngoc

    March 24, 2014 at 3:44 pm

    Hello Guys,

    Currently, I missing erro like this. I registered in windows azure market place and registered my Microsoft Translate application so I have these ClientId and Client Secret keys but It work only in the first time, the second time I see message is below:

    TranslateApliException: Cannot find an active Azure Market Place Translator Subscription associated with the request credentials : ID=0728.V2_Json.Translate.3C2D66E7

    Could you please kindly help me fix it?

     
  27. Charles

    May 21, 2014 at 12:59 pm

    I have downloaded the files you’ve shared, but in my workspace (translatr.java) there is an error
    saying that ” ivSpeakEntered cannot be resolved or is not a field”. Can you please help me to solve it?Thanks for your hard work

     
  28. pvk

    June 18, 2014 at 9:50 am

    Hi,
    Im getting this error:
    java.lang.exception: Error retrieving translation :permission denied

    Please help

     
  29. tastychoky

    July 2, 2014 at 10:42 am

    really great app, you handled the exceptions very well. Keep going.

     
  30. Guila Rose Rubis

    September 14, 2014 at 12:07 pm

    where are these from?

    import com.memetix.mst.language.Language;
    import com.memetix.mst.translate.Translate;

     
    • Gilbert Kimutai

      October 6, 2014 at 5:17 pm

      They come from the library jar.

       
  31. ofek

    November 6, 2014 at 2:29 pm

    I am using the code from my emulator, and I get exception –
    java.lang.Exception: [microsoft-translator-api] Error retrieving translation : Not trusted server certificate.

    I read somewhere that this has something to do with the microsoft certificate.

    what should I do to fix it? I want it to run on the emulator.
    and will it work on a device?
    thnaks

     
  32. dimvolk

    March 13, 2015 at 11:17 pm

    Nice!!! You help me.
    Thank you very much

     
  33. fabian

    April 7, 2015 at 9:45 am

    thats not german hahhahahah i am from germany and that sounds like tarzan german

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: