Language Translator and Text-To-Speech in Android

Introduction

 
Today we will make a language translator. Language translators are very important, especially for people who travel abroad. This app allows users to speak any language the user wants without even knowing that language.
 
In this app, the user will enter the text that he/she wants to convert. The user will get the translated text on a button click. The user will not only be able to read but hear the translated text. 
 
Step 1
 
We will be using Microsoft Translator for this. Prior to making this app, you will need to register yourself in the "Microsoft Marketplace". For registering, visit http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx. We will be using the "Client ID" and "Client Secret" provided in this app.
 
Step 2
 
Download the "microsoft-translator-java-api-0.6.1-jar-with-dependenciesjar" file provided in "library.rar" above.
 
Include this jar as a library in the Eclipse project for your language translator.
 
Step 3
 
"string.xml" used in this app is:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.   <string name="app_name">LangTranslatoeFinal</string>  
  4.   <string name="action_settings">Settings</string>  
  5.   <string name="hello_world">Hello world!</string>  
  6.    
  7.   <string name="choose_lang">Choose Language</string>  
  8.    
  9.   <string-array name="lang">  
  10.     <item>ENGLISH</item>  
  11.     <item>FRENCH</item>  
  12.     <item>GERMAN</item>  
  13.     <item>ITALIAN</item>      
  14.   </string-array>  
  15.    
  16. </resources>  
Step 4
 
Open "activity_main" and add the following code to it:
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.                 xmlns:tools="http://schemas.android.com/tools"  
  3.                 android:layout_width="match_parent"  
  4.                 android:layout_height="match_parent"  
  5.                 android:background="#ffd088">  
  6.   <EditText  
  7.           android:id="@+id/text"  
  8.           android:layout_width="wrap_content"  
  9.           android:layout_height="wrap_content"  
  10.           android:layout_alignParentTop="true"  
  11.           android:layout_centerHorizontal="true"  
  12.           android:layout_marginTop="31dp"  
  13.           android:ems="10" >  
  14.     <requestFocus />  
  15.   </EditText>  
  16.    
  17.   <LinearLayout  
  18.       android:layout_height="wrap_content"  
  19.       android:layout_width="fill_parent"  
  20.           android:orientation="vertical" >  
  21.     <TextView  
  22.             android:id="@+id/translatedtext"  
  23.             android:layout_width="wrap_content"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_below="@+id/etUserText"  
  26.             android:layout_centerHorizontal="true"  
  27.             android:layout_marginTop="168dp"  
  28.             android:text=""  
  29.             android:layout_marginLeft="90dp"  
  30.             android:textAppearance="?android:attr/textAppearanceLarge" />  
  31.     <Spinner  
  32.             android:id="@+id/selectLanguage"  
  33.             android:layout_width="wrap_content"  
  34.             android:layout_height="wrap_content"  
  35.             android:layout_below="@+id/etUserText"  
  36.             android:layout_centerHorizontal="true"  
  37.             android:layout_marginTop="50dp"  
  38.             android:prompt="@string/choose_lang"  
  39.             android:entries="@array/lang"  
  40.             android:layout_marginLeft="90dp"/>  
  41.     <Button  
  42.             android:id="@+id/say"  
  43.             android:layout_width="wrap_content"  
  44.             android:layout_height="wrap_content"  
  45.             android:layout_below="@+id/tvTranslatedText"  
  46.             android:layout_centerHorizontal="true"  
  47.             android:layout_marginTop="46dp"  
  48.             android:text="Say"  
  49.             android:background="@drawable/button_lay"  
  50.              android:layout_marginLeft="100dp" />  
  51.   </LinearLayout>  
  52. </RelativeLayout>  
EditText will take the text from the user that needs to be converted.
 
TextView will display the translated text.
 
Spinner is for the user to choose the language in which he/she wants to translate the entered text.
 
Button click will display the translated text and voice.
 
The layout looks like:
 
im1.jpg
 
Step 5
 
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.langtranslatoefinal;  
  2.    
  3. import java.util.Locale;  
  4.    
  5. import android.app.Activity;  
  6. import android.content.Intent;  
  7. import android.os.AsyncTask;  
  8. import android.os.Bundle;  
  9. import android.speech.tts.TextToSpeech;  
  10. import android.util.Log;  
  11. import android.view.Menu;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.widget.Button;  
  15. import android.widget.EditText;  
  16. import android.widget.Spinner;  
  17. import android.widget.TextView;  
  18. import android.widget.Toast;  
  19.    
  20. import com.memetix.mst.language.Language;  
  21. import com.memetix.mst.translate.Translate;  
  22.    
  23. public class MainActivity extends Activity implements TextToSpeech.OnInitListener {  
  24.         
  25.        private int check_code = 0;  
  26.        Spinner lang;  
  27.        Button say;  
  28.        EditText text;  
  29.        TextView translatedText;  
  30.        String original=null;  
  31.        String translated=null;  
  32.        String langSelected;  
  33.        private TextToSpeech convert;  
  34.    
  35.        @Override  
  36.        protected void onCreate(Bundle savedInstanceState) {  
  37.               super.onCreate(savedInstanceState);  
  38.               setContentView(R.layout.activity_main);  
  39.                
  40.               lang=(Spinner)findViewById(R.id.selectLanguage);  
  41.               say=(Button)findViewById(R.id.say);  
  42.               text=(EditText)findViewById(R.id.text);  
  43.               translatedText=(TextView)findViewById(R.id.translatedtext);  
  44.                
  45.               Intent check = new Intent();  
  46.         check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);  
  47.         startActivityForResult(check, check_code);  
  48.    
  49.         say.setOnClickListener(new OnClickListener() {  
  50.                       
  51.                      @Override  
  52.                      public void onClick(View v) {  
  53.                                    
  54.                          class bgStuff extends AsyncTask<Void, Void, Void>{                     
  55.                      
  56.                     @Override  
  57.                     protected Void doInBackground(Void... params) {  
  58.                         // TODO Auto-generated method stub                         
  59.                             
  60.                          Translate.setClientId("CLIENT ID"); //Change this  
  61.                          Translate.setClientSecret("CLIENT SECRET");  //Change this  
  62.                             
  63.                            Log.i("calling....................","speak");  
  64.                            original=text.getText().toString();  
  65.                            Log.i("Original Text is.............",original);  
  66.                            langSelected=String.valueOf(lang.getSelectedItem());  
  67.                            Log.i("Language selected.........",langSelected);  
  68.                               
  69.                            if (text!=null && text.length()>0) {      
  70.                                   try  
  71.                                   {  
  72.                                          if(langSelected.equalsIgnoreCase("ENGLISH"))  
  73.                                          {  
  74.                                                 convert.setLanguage(Locale.US);  
  75.                                                 translated = Translate.execute(original, Language.ENGLISH);  
  76.                                                 Log.i("translated text................", translated);                                                 
  77.                                          }  
  78.                                          else if(langSelected.equalsIgnoreCase("GERMAN"))  
  79.                                          {  
  80.                                                 convert.setLanguage(Locale.GERMAN);  
  81.                                                 translated = Translate.execute(original, Language.GERMAN);  
  82.                                                 Log.i("translated text................", translated);                                                 
  83.                                          }  
  84.                                          else if(langSelected.equalsIgnoreCase("FRENCH"))  
  85.                                          {  
  86.                                                 convert.setLanguage(Locale.FRENCH);  
  87.                                                 translated = Translate.execute(original, Language.FRENCH);  
  88.                                                 Log.i("translated text................", translated);                                   
  89.                                          }  
  90.                                          else if(langSelected.equalsIgnoreCase("ITALIAN"))  
  91.                                          {  
  92.                                                 convert.setLanguage(Locale.ITALIAN);  
  93.                                                 translated = Translate.execute(original, Language.ITALIAN);  
  94.                                                 Log.i("translated text................", translated);                                          
  95.                                          }                                         
  96.                                   }  
  97.                                   catch(Exception e)  
  98.                                   {  
  99.                                          Log.i("Error in translation.........",e.toString());  
  100.                                   }  
  101.                            }  
  102.                            return null;  
  103.                                    }                    
  104.    
  105.                            @Override  
  106.                            protected void onPostExecute(Void result) {  
  107.                            translatedText.setText(translated);  
  108.                            Toast.makeText(MainActivity.this"Saying: " + translated, Toast.LENGTH_LONG).show();  
  109.                            convert.speak(translated, TextToSpeech.QUEUE_ADD, null);  
  110.                             
  111.                            }  
  112.                            }  
  113.                          new bgStuff().execute();                            
  114.                      }  
  115.               });            
  116.        }  
  117.    
  118.        @Override  
  119.        public boolean onCreateOptionsMenu(Menu menu) {  
  120.               // Inflate the menu; this adds items to the action bar if it is present.  
  121.               getMenuInflater().inflate(R.menu.main, menu);  
  122.               return true;  
  123.        }  
  124.         
  125.        protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  126.         if (requestCode == check_code) {  
  127.             if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {  
  128.                 // success, create the TTS instance  
  129.                 convert = new TextToSpeech(thisthis);  
  130.             }  
  131.             else {  
  132.                 // missing data, install it  
  133.                 Intent installIntent = new Intent();  
  134.                 installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);  
  135.                 startActivity(installIntent);  
  136.             }  
  137.         }  
  138.     }  
  139.    
  140.     @Override  
  141.     public void onInit(int status) {  
  142.         if (status == TextToSpeech.SUCCESS) {  
  143.             Toast.makeText(MainActivity.this,"Engine is initialized", Toast.LENGTH_LONG).show();  
  144.              
  145.             int result = convert.setLanguage(Locale.GERMAN);  
  146.              
  147.             if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {  
  148.                 Log.i("TTS""This Language is not supported");  
  149.             }  
  150.             else {                  
  151.                 //speakOut("Ich");  
  152.               Log.i("TTS""This Language is supported");  
  153.             }  
  154.         }  
  155.         else if (status == TextToSpeech.ERROR) {  
  156.             Toast.makeText(MainActivity.this,"Error occurred while initializing engine", Toast.LENGTH_LONG).show();  
  157.         }  
  158.     }  
  159. }  
Text-To-Speech (TTS), also known as "speech synthesis", enables your Android device to "speak" text of various languages. The TextToSpeech engine supports many languages, like English, Spanish, German, Italian and so on.
 
In the code above, convert is an object of TextToSpeech.
 
The "convert.setLanguage" function will allow you to produce the voice in the accent of the specified country. Some languages are spoken with a different accent in different countries. You will clearly be able to see what difference it makes if you use this without the Translate.execute function.
 
The "Translate.execute" function performs language translation.
 
The "convert.speak" function will produce the voice.
 
Note that the code above will not work until and unless you give your "CLIENT ID" and "CLIENT SECRET" provided to you during registration, in "Translate.setClientId" and "Translate.setClientSecret" respectively. 
 
Step 6
 
Add the internet permission in "AndroidManifest.xml" as in the following:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.chhavi.langtranslatoefinal"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.   <uses-permission android:name="android.permission.INTERNET"/>  
  8.    
  9.   <uses-sdk  
  10.       android:minSdkVersion="8"  
  11.       android:targetSdkVersion="17" />  
  12.    
  13.   <application  
  14.       android:allowBackup="true"  
  15.       android:icon="@drawable/ic_launcher"  
  16.       android:label="@string/app_name"  
  17.       android:theme="@style/AppTheme" >  
  18.     <activity  
  19.         android:name="com.chhavi.langtranslatoefinal.MainActivity"  
  20.         android:label="@string/app_name" >  
  21.       <intent-filter>  
  22.         <action android:name="android.intent.action.MAIN" />  
  23.    
  24.         <category android:name="android.intent.category.LAUNCHER" />  
  25.       </intent-filter>  
  26.     </activity>  
  27.   </application>  
  28. </manifest>  
Output snapshots:
 
Run this application on an Android phone.
 
im2f.png
 
Enter the text.
 
im3f.png
 
Clicking on the Spinner will give you the following language list:
 
im4f.png
 
Choosing "German" from the spinner and clicking on the "Say" button will give you (note that you will hear the translated text at this time):
 
im5f.png
 
Translating into  "Italian":
 
im6f.png
 
Translating into "French":
 
im7f.png
 
Similarly, you can type text in any of these languages and get the translated text in the required language.
 

Summary

 
In this article, you learned two things: how to convert text to speech (accent taken care of) and how to translate text into some other language.
 
Thank you....... Enjoy coding :)


Similar Articles