RSS

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

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

 

App

 

 
Screenshot_2013-02-04-08-22-52

Screenshot_2013-02-04-08-23-00

Screenshot_2013-02-04-08-23-09

Screenshot_2013-02-04-14-22-04

 
Leave a comment

Posted by on February 4, 2013 in Uncategorized

 

Android Tutorials – Load image from URL to an ImageView

Loading an image that isn’t defined in your resource folder in android can be really tricky. The image has to be downloaded asynchronously, cached in the phone in case we want to reuse later and then display it in the ImageView. Luckily there are many libraries that do just that and better. I am going to be using the ImageLoader lib.

    1. Download the ImageLoader lib here. (Google ‘android ImageLoader’ if link fails)
    2. Place the jar file in the libs folder in your project.
    3. This piece of code should do the trick:
String image_url = "https://mycodeandlife.files.wordpress.com/2013/01/384088_2317070728022_2086719259_n.jpg";
ImageView image = (ImageView) findViewById(R.id.imageView1);
                        // Get singletone instance of ImageLoader
			ImageLoader imageLoader = ImageLoader.getInstance();
			// Initialize ImageLoader with configuration. Do it once.
			imageLoader.init(ImageLoaderConfiguration.createDefault(this));
			// Load and display image asynchronously

			DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showStubImage(R.drawable.ic_launcher) //this is the image that will be displayed if download fails
			.cacheInMemory()
			.cacheOnDisc()
			.build();

			imageLoader.displayImage(image_url, image, options);

This is the image. 384088_2317070728022_2086719259_n

The last bit is to add permissions to the Android Manifest. Add the following permissions: android.permission.WRITE_EXTERNAL_STORAGE and android.permission.INTERNET.

That’s it. Of course there still a lot more. You can use this in a list view and even show progress. You can read more here

 
8 Comments

Posted by on January 28, 2013 in Uncategorized

 

Eureka

presentation

Its been a great year. with Eureka, an app I built, wining some awards. Below are just photos.

Vodacom:

532442_10152312105005084_694451361_n Developer on stage 12 The final 3 winners Mbugua-Njihia-and-Gilbert-Rono 556326_10152312104395084_569384525_n

Safaricom:

29601_3964874315979_1039503236_nMbugua-Njihia-and-Gilbert-Rono

 
Leave a comment

Posted by on December 31, 2012 in Uncategorized

 

The Agora

“Power is in the hands not of the minority but of the whole people.When it is a question of settling private disputes,everyone is equal before the law; when it is  a question of putting one person before another in positions of public responsibility,what counts is not the membership of a particular class,but the actual ability which the man possesses.No one so long as he has it in him to be of service to the state,should be kept in political obscurity because of poverty………..” Pericles view on democracy

“When your spirit is strained and you limited to change
The lyrics in your limericks will change
A different hook, the way the sentences arranged
More demented in your deliverance, more sinister in your slang..”

The Question :“Are Political structure and Ideological developments Independent of Economic changes?”

Early historians believed that history was primarily influenced by spiritual and intellectual changes.This idea progressively changed as…

View original post 774 more words

 
Leave a comment

Posted by on November 28, 2012 in Uncategorized

 

De Morgan’s law

Hey so a bit of math here.

So I want to prove:  (A U B)’ = A’ ∩ B’ —> De Morgan’s law.

General case: In set theory, at least how I remember it is, if A = B then A is a subset of B and B a subset of A. Which is really obviously true. In mathy terms A ⊆ B and B ⊆ A. (⊆ means subset).

So what we want to do here is prove that (A U B)’ ⊆ A’ ∩ B’ and then prove also A’ ∩ B’ ⊆ (A U B)’ – just reversed the order.

STEP 1 – (A U B)’ ⊆ A’ ∩ B’

General case: The prove that A ⊆ B (A is a subset of B)  we show that there is a value common to both A and B.

suppose x ∈ (A U B)’ (∈ means ‘is contained in’). This wuld mean that x ∉ A U B and hence x ∉ A and x ∉ B (draw a Venn diagram if this is not too clear). which leads us to x ∈ A’ and x ∈ B’when combined is x ∈ A’ ∩ B’

And hence we have proven that x is in both A’ ∩ B’ and (A U B)’ which means (A U B)’ ⊆ A’ ∩ B’

STEP 2 – A’ ∩ B’ ⊆ (A U B)’

Try this on your own.

……………………

and finally (A U B)’ = A’ ∩ B’

 
Leave a comment

Posted by on November 21, 2012 in Uncategorized

 

Coder/Blogger/Subaru Fan

So he is finally graduating ….yes Jaymo is finally getting that piece of paper that will persuade mum that all the money she spent on me was not wasted. So as I was thinking of going for my Gown at Juja  a pal of mine asked me what I would tell the younger version of me if I could teleport back to 2008. back to when I was a freshman at JKUAT. Well after much pondering I came up with a list of the things I would tell first year Jaymo.

1.Campus will be over  before you know it,so have fun.I know it seems like all those Math lessons last forever but before you know it you will be doing your finals asking the crew when you will be having the last rave.You will have mad fun, you will get into trouble also…but the guys you call the crew will make campo rock the most. Marto,Pato,Ritchie,Mogaka,kush,mash and Brayo will have the weirdest plots.From kuchinja…

View original post 1,144 more words

 
Leave a comment

Posted by on November 21, 2012 in Uncategorized