📄 allspeechapp.java
字号:
//import statements
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.speech.*;
import javax.speech.recognition.*;
import javax.speech.synthesis.*;
import java.util.Locale;
import java.io.FileReader;
import java.awt.Color;
import java.net.*;
import java.sql.*;
public class AllSpeechApp extends ResultAdapter
{
/**
* Common declarations and initializations:
*/
JPanel pane;
JLabel label, head2, OrderRefNum_label,Name_label,email_label,label_status;
JTextField order_rn,Name;
JButton submit,cancel;
JRadioButton email_yes,email_no;
String newWord1="";
String orderStatus_DB="";
String email_status_y, email_status_n;
static JFrame frame = new JFrame("Speech-Text-Speech - Check order Status");
boolean success_Name=false,email_statusNO, email_statusYES;
int ordNum=0; String orderNumber="";
static Recognizer rec;
//Database Related Declarations
Connection theConnection;
ResultSet theResult1;
Statement theStatement1;
String driver="sun.jdbc.odbc.JdbcOdbcDriver"; // Replace it with your JDBC driver name.
String dbuser="satishs"; // Replace it with your database login id.
String dbpasswd="SSSSSS"; // Replace it with your database password.
String db="MyLearning"; // Replace it with your database name.
String driver_db="jdbc:odbc:";
String DRIVERDB=driver_db.concat(db);
//Fonts
Font HEADER_FONT= new Font("ARIAL", 1, 16);
Font NORMAL_FONT= new Font("ARIAL", 0, 6);
/**
* createComponents - creates a pane and add header label to it.
*/
public Component createComponents(String printText)
{
pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(
10, //top
10, //left
10, //bottom
10) //right
);
label = new JLabel("Find Status of your order : ");
label.setFont(HEADER_FONT);
label.setForeground(new Color(0,0,238));
pane.add(label);
return pane;
}
/**
* Creates a database connection, and gets the order_status from the Orders table.
* Writes the text on the panel.
* Speaks the text as 'Order number <order number> is <order status>'.
*/
public void getResult(String orderNum)
{
try
{
//Loading Sun's JDBC ODBC Driver
Class.forName(driver);
theConnection = DriverManager.getConnection(DRIVERDB,dbuser,dbpasswd);
theStatement1=theConnection.createStatement();
theResult1=theStatement1.executeQuery("SELECT orstat from orders where orrfnbr="+orderNum);
while(theResult1.next())
{
orderStatus_DB=theResult1.getString("orstat");
}
theResult1.close(); //Close the result set
theStatement1.close(); //Close statement
theConnection.close(); //Close the connection
String part1= "Order Number "+orderNum+" is ";
if(orderStatus_DB.equals("C"))
{
orderStatus_DB="Completed.";
}
else if(orderStatus_DB.equals("P"))
{
orderStatus_DB="Pending.";
}
else if(orderStatus_DB.equals("X"))
{
orderStatus_DB="Cancelled.";
}
String displayOrdStatus=part1.concat(orderStatus_DB);
//Writes the text on the panel
createForm("label_status",displayOrdStatus);
//Speaks the text
MySpeech(displayOrdStatus);
//Set the focus back to the Name field.
Name.requestFocus();
//Repaint the panel
pane.repaint();
}
catch(Exception e)
{
System.out.println("Exception in getResult : " +e);
}
}
/**
* Listens and stores the spoken text.
* This is Speech Recognition method.
* This method also writes the text on the screen using CreateForm() method.
*/
public void resultAccepted(ResultEvent e)
{
try
{
Result r = (Result)(e.getSource());
ResultToken tokens[] = r.getBestTokens();
for(int i=0;i<tokens.length;i++)
{
newWord1 = newWord1.concat(tokens[i].getSpokenText());
newWord1 = newWord1.concat(" ");
}
int len_tokens= tokens.length;
if(len_tokens==2)
{
String name = tokens[0].getSpokenText().concat(" ");
name=name.concat(tokens[1].getSpokenText());
success_Name = createForm("Name",name);
}
if(success_Name)
{
order_rn.requestFocus();
//Sets the order number in the form
if(len_tokens == 1)
{
order_rn.setText("");
int numstarts = newWord1.indexOf("1");
orderNumber = newWord1.substring(numstarts,numstarts+2);
order_rn.setText(orderNumber);
}
//Sets the order email notification flag to yes or no.
int email_status_yes = newWord1.indexOf("Yes");
int email_status_no = newWord1.indexOf("No");
if(email_status_yes>0)
{
email_status_y = newWord1.substring(email_status_yes,newWord1.length());
email_yes.setSelected(true);
submit.requestFocus();
}
else if(email_status_no>0)
{
email_status_n = newWord1.substring(email_status_no,newWord1.length());
email_no.setSelected(true);
submit.requestFocus();
}
email_statusYES=email_yes.isSelected();
email_statusNO =email_no.isSelected();
/* Checks if shopper said 'Submit'. If so, submit the form by calling getResult() method. */
int submitStarts = newWord1.indexOf("Submit");
if(submitStarts > 0)
{
int numstarts = newWord1.indexOf("1");
orderNumber = newWord1.substring(numstarts,numstarts+2);
//Get order status from the Database
getResult(orderNumber);
newWord1="";
Name.setText("");
order_rn.setText("");
email_yes.setSelected(false);
email_no.setSelected(false);
}
/* Checks if shopper said 'Cancel'. If so, resets the form. */
int cancelStarts = newWord1.indexOf("Cancel");
if(cancelStarts > 0)
{
Name.requestFocus();
newWord1="";
Name.setText("");
order_rn.setText("");
email_yes.setSelected(false);
email_no.setSelected(false);
}
}
}
catch (Exception e2)
{
System.out.println("\n EXCEPTION in resultAccepted :\n"+e2);
}
//Finish setting up the frame, and show it.
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
frame.setSize(600,275);
frame.setVisible(true);
}
/**
* The parameter passed in this method is spoken by the computer.
* This is Speech Synthesis (Text To Speech) method.
*/
public void MySpeech(String SpeakText)
{
try
{
// Create a synthesizer for English
Synthesizer synth = Central.createSynthesizer(new SynthesizerModeDesc(Locale.ENGLISH));
// Get it ready to speak
synth.allocate();
synth.resume();
//Speak Now...
synth.speakPlainText(SpeakText, null);
// Wait till speaking is done
synth.waitEngineState(Synthesizer.QUEUE_EMPTY);
// Clean up
synth.deallocate();
}
catch (Exception e1)
{
System.out.println("EXCEPTION in MySpeech :" + e1);
}
}
/**
* Creates the form.
*/
public boolean createForm(String fieldName,String PrintText)
{
Component contents = createComponents("");
frame.getContentPane().add(contents,BorderLayout.CENTER);
pane.setLayout(new GridLayout(8,3,2,2));
//Instantiate all components
Name_label = new JLabel("Enter Your Name :");
label_status = new JLabel("label_status");
OrderRefNum_label = new JLabel("Enter Order Number :");
email_label = new JLabel("Did you get an email confirmation for your order?");
Name = new JTextField("",30);
order_rn = new JTextField("",5);
email_yes = new JRadioButton("Yes");
email_no = new JRadioButton("No");
ButtonGroup group = new ButtonGroup();
submit = new JButton("Submit");
cancel = new JButton("Cancel");
JLabel blank1 = new JLabel(" ");
JLabel head2 = new JLabel("[Voice Only Mode]");
//Set attributes
head2.setForeground(new Color(0,0,238));
submit.setBackground(new Color(0,0,128));
submit.setForeground(Color.white);
cancel.setBackground(new Color(0,0,128));
cancel.setForeground(Color.white);
group.add(email_yes);
group.add(email_no);
Name_label.setForeground(new Color(139,37,0));
OrderRefNum_label.setForeground(new Color(139,37,0));
email_label.setForeground(new Color(139,37,0));
//Add all components
head2.setFont(HEADER_FONT);
pane.add(head2);
pane.setFont(NORMAL_FONT);
pane.add(Name_label);
pane.add(Name);
pane.add(OrderRefNum_label);
pane.add(order_rn);
pane.add(email_label);
pane.add(email_yes);
pane.add(blank1);
pane.add(email_no);
pane.add(submit);
pane.add(cancel);
if(fieldName.equals("Name"))
{
Name.setText("");
Name.setText(PrintText);
order_rn.setText("");
email_yes.setSelected(false);
email_no.setSelected(false);
return true;
}
else if(fieldName.equals("order_rn"))
order_rn.setText(PrintText);
else if(fieldName.equals("label_status"))
{
pane.add(label_status);
label_status.setText(PrintText);
label_status.setForeground(Color.red);
label_status.setFont(HEADER_FONT);
}
else
{
return false;
}
return false;
}
/**
* Main Method.
*/
public static void main(String[] args)
{
AllSpeechApp ASApp = new AllSpeechApp();
ASApp.createForm("Name","");
try
{
// Create a recognizer that supports English.
rec = Central.createRecognizer(new EngineModeDesc(Locale.ENGLISH));
// Start up the recognizer
rec.allocate();
// Load the grammar from a file, and enable it (order_search.gram in this case).
FileReader reader = new FileReader(args[0]);
RuleGrammar gram = rec.loadJSGF(reader);
gram.setEnabled(true);
// Add the listener to get results
rec.addResultListener(new AllSpeechApp());
// Commit the grammar
rec.commitChanges();
// Request focus and start listening
rec.requestFocus();
rec.resume();
}
catch (Exception e3)
{
System.out.println("Exception in MAIN method : " + e3);
}
/**
*Displays the frame first time
*/
frame.setSize(600,275);
frame.setVisible(true);
frame.setResizable(false);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -