Speech Recognition

Hello Friends here is a simple code to develop a speech recognition in android.


I would suggest that you create a blank project for this, get the basics, then think about merging VR into your existing applications. I’d also suggest that you copy the code below exactly as it appears, once you have that working you can begin to tweak it.
With your blank project setup, you should have an AndroidManifest file like the following.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.jameselsey"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:label="VoiceRecognitionDemo" android:icon="@drawable/icon"
            android:debuggable="true">
        <activity android:name=".VoiceRecognitionDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

And have the following in res/layout/voice_recog.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:paddingBottom="4dip"
        android:text="Click the button and start speaking" />

    <Button android:id="@+id/speakButton"
        android:layout_width="fill_parent"
        android:onClick="speakButtonClicked"
        android:layout_height="wrap_content"
        android:text="Click Me!" />

    <ListView android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" />

 </LinearLayout>

And finally, this in your res/layout/main.xml :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="VoiceRecognition Demo!"
    />
</LinearLayout>


So thats your layout and configuration sorted. It will provide us with a button to start the voice recognition, and a list to present any words which the voice recognition service thought it heard. Lets now step through the actual activity and see how this works.

You should copy this into your activity :



package com.jameselsey;

import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;

/**
 * A very simple application to handle Voice Recognition intents
 * and display the results
 */
public class VoiceRecognitionDemo extends Activity
{

    private static final int REQUEST_CODE = 1234;
    private ListView wordsList;

    /**
     * Called with the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.voice_recog);

        Button speakButton = (Button) findViewById(R.id.speakButton);

        wordsList = (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)
        {
            speakButton.setEnabled(false);
            speakButton.setText("Recognizer not present");
        }
    }

    /**
     * Handle the action of the button being clicked
     */
    public void speakButtonClicked(View v)
    {
        startVoiceRecognitionActivity();
    }

    /**
     * Fire an intent to start the voice recognition activity.
     */
    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Voice recognition Demo...");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @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);
            wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
                    matches));
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}



Breakdown of what the activity does :

Declares a request code, this is basically a checksum that we use to confirm the response when we call out to the voice recognition engine, this value could be anything you want. We also declare a ListView which will hold any words the recognition engine thought it heard.

The onCreate method does the usual initialisation when the activity is first created. This method also queries the packageManager to check if there are any packages installed that can handle intents for ACTION_RECOGNIZE_SPEECH. The reason we do this is to check we have a package installed that can do the translation, and if not we will disable the button.



The speakButtonClicked is bound to the button, so this method is invoked when the button is clicked.



The startVoiceRecognitionActivity invokes an activity that can handle the voice recognition, setting the language mode to free form (as opposed to web form)

The onActivityResult is the callback from the above invocation, it first checks to see that the request code matches the one that was passed in, and ensures that the result is OK and not an error.

Next, the results are pulled out of the intent and set into the ListView to be displayed on the screen.



Notes on debugging :

You won’t have a great deal of luck running this on the emulator, there may be ways of using a PC microphone to direct audio input into the emulator, but that doesn’t sound like a trivial task. Your best bet is to generate the APK and transfer it over to your device



If you experience any crashing errors (I did), then connect your device via USB, enable debugging, and then run the following command from a console window

1
<android-home>/platform-tools/adb -d logcat
What this does, is invoke the android device bridge, the -d switch specifies to run this against the physical device, and the logcat tells the ADB to print out any device logging to the console.

This means anything you do on the device will be logged into your console window, it helped me find a few null pointer issues.



Thats quite a simple activity.  and if you have any comments please let me know. You may have mixed results with what the recognition thinks you have said, I’ve had some odd surprises, let me know!

Happy coding!

1 comments:

Snakes N Ladders Game Java

The Code Below Shows How To Develop SnakesNLadder Game

Step1 : Create a directory to store your snakesnladder image

Step2 : Create a java file and place a main JPanel. In This JPanel Place SnakenLadder Image.

Step 3 : Now place a new JLayeredPane. JLayeredPane Helps you to place panel above a panel. This panel will be a player that will move when the dice is played.

Step 4 : Take maximum width and maximum height of the main panel. Use maximum width as maximum X valu and maximum height as Maximum Y value.Initially  keep the players  position at maximum height and minimum width. Eg X=450 Y=450 then player.x = 25 and player.y = 425

Step 5 : Make a button that gives the dice value. Use this value to move the player. Eg if dice gives value as 6 then add 25 to player.x value till it reaches maximum X value.

Step 6 : If player.x reaches the Maximum X value, reduce the player.y value(eg if player.x = 425 then player.y = 400) and start reducing the player.x value till reaches to the minimum X value
Step 7 : Repeat this procedure till the player.x and player.y value reaches to the 100 block

Note : Even thought the code has the login snake bite and climbing ladder still you should use some logic for snake bite and ladder climbing to improve your logics


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.io.*;

public class SnakeLadder extends JFrame implements ActionListener
{
JPanel jp,southPanel,jp2,jp3,northPanel,smiley;
JLayeredPane jp1;
JLabel l1,l2,l3,l4,move,position;
private Timer timer,timer1;
private int delay = 50,delay1 = 1000;
int i=1,j=1,counter=1, x = 10, y = 370, swt = 1, score = 500, moves = 0,a=10,b=370,cur_pos=1,cur_pos1=1;
JButton btnStart,btnStop,btnPlay,btnUndo;
public SnakeLadder()
{
jp = (JPanel)getContentPane();
jp.setLayout(new BorderLayout());
southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
northPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
jp1 = new JLayeredPane();
jp2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
jp3 = new JPanel(new FlowLayout(FlowLayout.CENTER));
smiley = new JPanel(new FlowLayout(FlowLayout.CENTER));
jp3.setBackground(Color.BLUE);
smiley.setBounds(-10,-10,15,20);
jp3.setBounds(10,370,20,20);
jp2.setBounds(0,0,400,400);
l1 = new JLabel("Score = 500");
l2 = new JLabel("Ladders");
l3 = new JLabel("Snakes");
l4 = new JLabel("1");
position = new JLabel("Position = 1");
move = new JLabel("Moves = 0");
btnStart = new JButton("Start");
btnStop = new JButton("Stop");
btnPlay = new JButton("New Game");
btnUndo = new JButton("Undo");
timer = new Timer(delay,new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
if(i > 0)
                {
                    if(i != 7)
{
counter = i;
                    l4.setText("" + counter);
i++;
}
else
{
i = 1;
}
                }
}
});

timer1 = new Timer(delay1,new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
//jp3.setBounds(x,y,20,20);
timer1.stop();
}
});
jp.add(jp1,BorderLayout.CENTER);
jp2.setOpaque(true);
JLabel background=new JLabel(new ImageIcon("Snakes-Ladders.jpg"));
JLabel background1=new JLabel(new ImageIcon("smileyevil.png"));
jp2.add(background);
smiley.add(background1);
jp1.add(jp2, new Integer(0),0);
jp1.add(jp3, new Integer(1),0);
jp1.add(smiley, new Integer(2),0);
//smiley.setVisible(false);
jp.add(northPanel,"North");
jp.add(l2,"East");
jp.add(l3,"West");
jp.add(southPanel,"South");
southPanel.add(btnStart);
southPanel.add(btnStop);
southPanel.add(btnPlay);
southPanel.add(btnUndo);
southPanel.add(l4);
northPanel.add(l1);
northPanel.add(move);
northPanel.add(position);
btnStart.addActionListener(this);
btnStop.addActionListener(this);
btnPlay.addActionListener(this);
btnUndo.addActionListener(this);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == btnUndo)
{
x = a;
y = b;
moves++;
jp3.setBounds(x,y,20,20);
score = score - 5;
if(y == 330 || y == 250 || y == 170 || y == 90 || y == 10)
{
swt = 2;
}
else //if(x == 370 || x == 290 || x == 210 || x == 130 || x == 80)
{
swt = 1;
}
System.out.println("X = " + x + " Y = " + y);
}
if(ae.getSource() == btnPlay)
{
        timer.stop();
btnStop.setEnabled(true);
btnStart.setEnabled(true);
i=1;j=1;counter=1; x = 10; y = 370; swt = 1; score = 500; moves = 0;a=10;b=370;cur_pos=1;
jp3.setBounds(x,y,20,20);
l1.setText("Score = 500");
l4.setText("1");
position.setText("Postion = 1");
move.setText("Moves = 0");
}
if(ae.getSource() == btnStart)
{
smiley.setVisible(false);
        timer.start();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
score= score - 5;
l1.setText("Score = " + score);
}
if(ae.getSource() == btnStop)
{
        timer.stop();
System.out.println("Counter = " + counter);
btnStart.setEnabled(true);
btnStop.setEnabled(false);
moves++;
a = x;
b = y;
if(x == 10 && y == 370 && counter != 6)
{
counter = 1;
}
if(x == 10 && y == 370)
{
counter--;
}
if(x == 210 && y == 10 && counter > 5)
{}
else if(x == 170 && y == 10 && counter > 4)
{}
else if(x == 130 && y == 10 && counter > 3)
{}
else if(x == 90 && y == 10 && counter > 2)
{}
else if(x == 50 && y == 10 && counter > 1)
{}
else
{
while(j <= counter)
{
if(swt == 1)
{
if(x == 370)
{
if(counter == 1)
{
y = y - 40;
swt = 2;
}
else
{
x = 370;
y = y - 40;
swt = 2;
}
}
else
{
x = x + 40;
}
j++;
}
if(swt == 2)
{

if(x == 10)
{
if(counter == 1)
{
y = y - 40;
swt = 1;
}
else
{
x = 10;
y = y - 40;
swt = 1;
}
}
else
{
x = x - 40;
}
j++;
}
}
j = 1;
timer1.start();
jp3.setBounds(x,y,20,20);
}

move.setText("Moves = " + moves);

// LADDERS

if(x == 130 && y == 370)
{
x = 250;
y = 330;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 330 && y == 370)
{
x = 370;
y = 250;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 50 && y == 330)
{
x = 90;
y = 250;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 10 && y == 290)
{
x = 50;
y = 210;
jp3.setBounds(x,y,20,20);
swt = 1;
}
if(x == 290 && y == 290)
{
x = 130;
y = 50;
jp3.setBounds(x,y,20,20);
swt = 1;
}
if(x == 370 && y == 170)
{
x = 250;
y = 130;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 370 && y == 90)
{
x = 370;
y = 10;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 10 && y == 90)
{
x = 10;
y = 10;
jp3.setBounds(x,y,20,20);
//swt = 2;
}
// SNAKES
if(x == 130 && y == 330)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 250;
y = 370;
jp3.setBounds(x,y,20,20);
swt = 1;
}
if(x == 250 && y == 170)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 250;
y = 250;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 50 && y == 130)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 50;
y = 330;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 130 && y == 130)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 10;
y = 170;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 250 && y == 50)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 130;
y = 290;
jp3.setBounds(x,y,20,20);
swt = 1;
}
if(x == 290 && y == 10)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 290;
y = 90;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 210 && y == 10)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 210;
y = 90;
jp3.setBounds(x,y,20,20);
swt = 2;
}
if(x == 90 && y == 10)
{
smiley.setVisible(true);
smiley.setBounds(x,y,15,20);
x = 50;
y = 90;
jp3.setBounds(x,y,20,20);
swt = 2;
}
System.out.println("X = " + x + " Y = " + y);

// Position

if(y == 370)
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 1;
position.setText("Position = " + cur_pos);

}
if(y == 330)
{
cur_pos = (x - 10)/40;
cur_pos = 10 - cur_pos + 10;
position.setText("Position = " + cur_pos);

}
if(y == 290)
{
if(x == 10)
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 1 + 20;
position.setText("Position = " + cur_pos);
}
else
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 21;
position.setText("Position = " + cur_pos);
}

}
if(y == 250)
{
cur_pos = (x - 10)/40;
cur_pos = 10 - cur_pos + 30;
position.setText("Position = " + cur_pos);

}
if(y == 210)
{
if(x == 10)
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 1 + 40;
position.setText("Position = " + cur_pos);
}
else
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 41;
position.setText("Position = " + cur_pos);
}

}
if(y == 170)
{
cur_pos = (x - 10)/40;
cur_pos = 10 - cur_pos + 50;
position.setText("Position = " + cur_pos);

}
if(y == 130)
{
if(x == 10)
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 1 + 60;
position.setText("Position = " + cur_pos);
}
else
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 61;
position.setText("Position = " + cur_pos);
}

}
if(y == 90)
{
cur_pos = (x - 10)/40;
cur_pos = 10 - cur_pos + 70;
position.setText("Position = " + cur_pos);

}
if(y == 50)
{
if(x == 10)
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 1 + 80;
position.setText("Position = " + cur_pos);
}
else
{
cur_pos = (x - 10)/40;
cur_pos = cur_pos + 81;
position.setText("Position = " + cur_pos);
}

}
if(y == 10)
{
cur_pos = (x - 10)/40;
cur_pos = 10 - cur_pos + 90;
position.setText("Position = " + cur_pos);

}
if(score == 0)
{
JOptionPane.showMessageDialog(this,"Game Over. Your Score is " + score);
int ans = JOptionPane.showConfirmDialog(this,"New Game","Game",JOptionPane.YES_NO_OPTION);
if(ans == JOptionPane.YES_OPTION)
{
        timer.stop();
btnStop.setEnabled(true);
btnStart.setEnabled(true);
i=1;j=1;counter=1; x = 10; y = 370; swt = 1; score = 500; moves = 0;a=10;b=370;
jp3.setBounds(x,y,20,20);
l1.setText("Score = 500");
l4.setText("1");
move.setText("Moves = 0");
position.setText("Position = 1");
}
else if(ans ==JOptionPane.NO_OPTION)
{
System.exit(0);
}
}
if(x == 10 && y == 10)
{
JOptionPane.showMessageDialog(this,"You Won. Your Score Is " + score);
int ans = JOptionPane.showConfirmDialog(this,"New Game","Game",JOptionPane.YES_NO_OPTION);
if(ans == JOptionPane.YES_OPTION)
{
        timer.stop();
btnStop.setEnabled(true);
btnStart.setEnabled(true);
i=1;j=1;counter=1; x = 10; y = 370; swt = 1; score = 500; moves = 0;a=10;b=370;
jp3.setBounds(x,y,20,20);
l1.setText("Score = 500");
l4.setText("1");
move.setText("Moves = 0");
position.setText("Position = 1");
}
else if(ans ==JOptionPane.NO_OPTION)
{
System.exit(0);
}
}
}
}

public static void main(String[] args)
{
SnakeLadder sl = new SnakeLadder();
sl.setSize(500,500);
sl.setVisible(true);
sl.setResizable(false);
}
}

2 comments: