Thursday, 18 July 2013

Text To Speech in Android

Hello Guys,  Hope You all are doing Well !!!.
Today I am going to put an example of Text to Speech(TTS) in Android. Assume You are working on a project in which if user want to listen the text . In that case You have to use TTS(Text To Speech)Api of Android.
The Android platform includes a TTS engine (android.speech.tts) that enables devices to perform speech synthesis. You can use the TTS engine to have your applications “read” text to the user. This feature used frequently with Location-Based Services (LBS) applications that allow for hands-free directions. Other applications use this feature for users who have reading or sight problems.
The Android TTS engine supports a variety of languages, including English (in American or British accents), French, German, Italian, and Spanish. The synthesized speech can be played immediately or saved to an audio file, which can be treated like any other audio file.

Here I am going to show the two use case of TTS. One is simple text to speech example(img1) and another 
is  speak time example(img2). 
just create following java files inside your src folder and xml file under layout folder of eclipse project 
Java File
1.TextToSpeechHome.java
2. TextToSpeechDemo1.java
3.TextToSpeechDemo2.java
Xml File
1. activity_texttospeech_home.xml
2. activity_texttospeech_demo1.xml
3. activity_texttospeech_demo2.xml
Manifest File
AndroidManifest.xml

Now put following simple code inside your java file one by one

1. TextToSpeechHome.java
 package com.sks.texttospeech;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class TextToSpeechHome extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_texttospeech_home);
findViewById(R.id.demo1_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), TextToSpeechDemo1.class));
}
});
findViewById(R.id.demo2_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent(getBaseContext(), TextToSpeechDemo2.class));
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_texttospeech_home, menu);
return true;
}
}
2. TextToSpeechDemo1.java
package com.sks.texttospeech;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class TextToSpeechDemo1 extends Activity implementsOnInitListener{
private TextToSpeech tts;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_texttospeech_demo1);
tts = new TextToSpeech(thisthis);
findViewById(R.id.sayit_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (tts!=null) {
String text = ((EditText)findViewById(R.id.speak_editText)).getText().toString();
if (text!=null) {
if (!tts.isSpeaking()) {
tts.speak(text, TextToSpeech.QUEUE_FLUSHnull);
}
}
}
}
});
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status==TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.getDefault());
else {
tts = null;
Toast.makeText(this"Failed to initialize TTS engine.", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (tts!=null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
3.TextToSpeechDemo2.java
package com.sks.texttospeech;
import java.util.Calendar;
import java.util.Locale;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
public class TextToSpeechDemo2 extends Activity implementsOnInitListener{
private TextToSpeech tts;
private int mHourmMinute;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_texttospeech_demo2);
tts = new TextToSpeech(thisthis);
findViewById(R.id.speaktime_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
String myTime= "Now is " + String.valueOf(mHour)+ " Hour "+String.valueOf(mMinute)+ " Minute";
tts.speak(myTime, TextToSpeech.QUEUE_FLUSHnull);
}
});
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {

int result = tts.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS""This Language is not supported");
else {
Log.e("TTS""This Language is supported");
}
else {
Log.e("TTS""Initilization Failed!");
}
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
Now xml file code
1. activity_texttospeech_home.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"
tools:context=".TextToSpeechHome" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="@string/hello_world"
android:textColor="#A52A2A"
android:textStyle="bold"
android:typeface="serif" />
<Button
android:id="@+id/demo1_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="40dp"
android:layout_marginTop="51dp"
android:text="Demo1" />
<Button
android:id="@+id/demo2_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="57dp"
android:layout_toRightOf="@+id/demo1_button"
android:text="Demo2" />
</RelativeLayout>
2. activity_texttospeech_demo1.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity" >
<Button
android:id="@+id/sayit_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/speak_editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:text="Say It" />
<EditText
android:id="@+id/speak_editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="77dp"
android:ems="10"
android:inputType="text"
android:text="Hello world!" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:textStyle="bold"
android:typeface="serif"
android:textColor="#A52A2A"
android:text="TTS Demonstration" />
</RelativeLayout>
3. activity_texttospeech_demo2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:textColor="#A52A2A"
android:typeface="serif"
android:text="Speaking Clock" />
<AnalogClock
android:id="@+id/analogClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"/>
<Button
android:id="@+id/speaktime_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"
android:text="Speak Time" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sks.texttospeech"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.sks.texttospeech.TextToSpeechHome"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.sks.texttospeech.TextToSpeechDemo1"/>
<activity android:name="com.sks.texttospeech.TextToSpeechDemo2"/>
</application>

</manifest>

This is all about source code for creating above TTS example. Now run your project and test your app by entering some text in input filed. 
Changing Language
You can change language to speak by using setLanguage() function. Lot of languages are supported like Canada, French, Chinese, Germany etc.,
tts.setLanguage(Locale.CHINESE); // Chinese language
Changing Pitch Rate
You can set speed pitch level by using setPitch() function. By default the value is 1.0 You can set lower values than 1.0 to decrease pitch level or greater values for increase pitch level.
tts.setPitch(0.6);
Changing Speed Rate
The speed rate can be set using setSpeechRate(). This also will take default of 1.0 value. You can double the speed rate by setting 2.0 or make half the speed level by setting 0.5
tts.setSpeechRate(2);
This is about TTS. For more detail you can visit Developer website of Android. 
    Happy Coding !!!

Custom Toast in Android

In android there are several way to information user by using pre-define classes/API. As for example Toast, Dialog, Notification these three are the main classes for user notification. Dialog has different types like Alert, Popup,Custom Dialog and more. Same way notification have type like local notification(based on services and AlertManager) and  server side notification like Urban Air Push and other third party notification.

  But Today I am going to deal Toast API in android and it uses in showing user information. By default We generally use simple Toast to show user information. But We can customize Toast message. So In this Post I am going to show all aspect of Toast message in Android.
At first Android official definition of Toast:- "A toast provides simple feedback about an operation in a small popup. It only fills the amount of space required for the message and the current activity remains visible and interactive.Toasts automatically disappear after a timeout. "

The Basics
First, instantiate a Toast object with one of the makeText() methods. This method takes three parameters: the application Context, the text message, and the duration for the toast.You can display the toast notification with show(), as shown in the following example:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
You can also call Toast message like this. 
Toast.makeText(context, text, duration).show();
Positioning  Toast on the Screen
A standard toast notification appears near the bottom of the screen, centered horizontally. You can change this position with the setGravity(int, int, int) method. This accepts three parameters: a Gravity constant, an x-position offset, and a y-position offset.
For example, if you decide that the toast should appear in the top-left  corner or Center-horizontal, you can set the gravity like this:

Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);//Top-left corner or Put Gravity.Center_horizental for center position 
toast.show();


Adding an Image to the Basic Toast
In order to add an image to the standard Toast, you first need to create an ImageView object, and set its image from the resources using the setImageResource method. You then need to get the standard view (which is actually a LinearLayout) and add the newly created ImageView object to it. The position, into which the image needs to be inserted, also should be set (in our case 0 is used, so that the image is displayed over the text). Code for this is shown below:
Toast toast = Toast.makeText(getApplicationContext(),"'saurabhsharma123k.blogspot.in'",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout toastView = (LinearLayout) toast.getView();
ImageView image = new ImageView(getApplicationContext());
image.setImageResource(R.drawable.saurabh);
toastView.addView(image, 0);
toast.show();

Creating a Toast with Custom Layout
In order to create a Toast with custom layout, we first need to create that layout itself. Its code is shown below:
  LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_activity,(ViewGroup) findViewById(R.id.llToast));
ImageView image = (ImageView) layout.findViewById(R.id.tvImageToast);
image.setImageResource(R.drawable.saurabh);
TextView title = (TextView) layout.findViewById(R.id.tvTitleToast);
title.setText("Attention");
TextView text = (TextView) layout.findViewById(R.id.tvTextToast);
text.setText("'saurabhsharma123k.blogspot.in'");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.RIGHT | Gravity.TOP, 12, 40);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

Calling a Toast from Another Thread
To call a Toast from another Thread, you need to define a property of Handler type in your class:
Handler handler = new Handler();
Now, let’s assume that we have a Thread, in which we need to call a method that displays a Toast:

new Thread(new Runnable() {
public void run() {
showToast();
}
}).start();

In this case, the method will be executed in a separate Thread. But because a Toast can only be displayed in the main Thread, So we will get an error when we try to run this.
If we need to execute in the main Thread, when calling from a separate Thread, you need a Handler, that was defined earlier. You can display a Toast from newly created Thread in this way:
public void showToast() {
handler.post(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"'saurabhsharma123k.blogspot.in'", Toast.LENGTH_SHORT).show();
}
});
}
                Happy Coding !!!

Build a Custom Kernel Module for Android

Hi Guys!!!Hope you are doing well !!!. Today I will describe how you can write a custom kernel module(Hello world) for Android and load it a...