Friday 19 July 2013

Voice Recognition(Speech to text) in Android


Hello Guys, Hope You all are doing well. Today  I am going to show an example on Voice recognition in Android. My Previous Post was on Text To speech . Now I am going to show  Speech to text and search it on Google.

Android natively provides feature of Speech to Text.Voice recognition featured in android is achieved using the RecognizerIntent.Use the Recognizer class in an intent to call the voice API.Internally voice recognition communicates with the server and gets the results. So you must provide the internet access permission for the application. Android Jelly Bean(API level 16) doesn’t  require internet connection to perform voice recognition.

Here we check for the recognizer in the device if available the speech to text happen else we show a toast displaying 'Recognizer Not Found'

Note: This application will not work in emulator since it does not have the recognizer, so test it in a device and it also requires an internet connection.



                 

Above given image is final  output of voice recognition working sample app. Just create a Android project named it VoiceRecognition in your Eclipse. Copy and paste following source code in your class. 
Java Class
1. VoiceActivity.java
Xml file
1. activity_voice.xml
Now put following code in your 
Voice Activity. java. 
package com.sks.texttospeech;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class VoiceActivity extends Activity{
private static final int REQUEST_CODE = 1234;
private ListView matchList;
Button speak_button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_recignition);
speak_button = (Button) findViewById(R.id.speakButton);
matchList = (ListView) findViewById(R.id.list);
// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0)
{
speak_button.setEnabled(false);
Toast.makeText(getApplicationContext(), "Recognizer Not Found", 1000).show();
}
speak_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startVoiceRecognitionActivity();
}
});
matchList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
String item = matchList.getAdapter().getItem(position).toString();
Toast.makeText(VoiceActivity.this, item + " selected", Toast.LENGTH_LONG).show();
Intent search = new Intent(Intent.ACTION_WEB_SEARCH);
search.putExtra(SearchManager.QUERY, item);
startActivity(search);
}
});
}
private void startVoiceRecognitionActivity()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
//1.LANGUAGE_MODEL_WEB_SEARCH : For short phrases
//2.LANGUAGE_MODEL_FREE_FORM : If not sure about the words or phrases and its domain.
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "saurabhsharma Voice Recognition...");
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
matchList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
}

Now Put following code in your 
activity_voice.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:gravity="center_horizontal"
android:textStyle="bold"
android:textColor="#A52A2A"
android:text="Click microPhone and start speaking" />
<Button
android:id="@+id/speakButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="@drawable/voic_img1" />
<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1" />
</LinearLayout>

Finally put internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
  Run this code on Actual Device and  Enjoy the Speech Api Of android.
                                       Happy Coding !!!

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

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