所以我正在构建一个 sphinx-4 程序,它只会在您按住 shift 按钮时进行监听。这样我就可以防止错误,并且只有在我按住 shift 按钮时它才会听我说。当我释放 shift 按钮时,我希望程序等到我再次按住它。当按下 ctrl-c 时,程序将完全退出。我正在使用 keylistener 来执行此操作。
我遇到的问题是程序确实在我按下 shift 按钮后开始收听,但是当我释放它时它不会停止收听。我不确定我的代码有什么问题。这是我创建的 MKeyListener 类中的内容:
public class MKeyListener implements KeyListener {
static ConfigurationManager cm;
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("Please hold down the shift button to have Sphinx listen.");
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_SHIFT)
{
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.allocate();
// start the microphone or exit if the programm if this is not possible
Microphone microphone = (Microphone) cm.lookup("microphone");
if (!microphone.startRecording()) {
System.out.println("Cannot start microphone.");
recognizer.deallocate();
System.exit(1);
}
System.out.println("Say: (Good morning | Hello) ( Bhiksha | Evandro | Paul | Philip | Rita | Will )");
// loop the recognition until the programm exits.
Boolean var = e.isShiftDown();
while (var == true) {
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
Result result = recognizer.recognize();
if (result != null) {
String resultText = result.getBestFinalResultNoFiller();
System.out.println("You said: " + resultText + '\n');
} else {
System.out.println("I can't hear what you said.\n");
}
var = e.isShiftDown();
System.out.println(var);
}
recognizer.deallocate();
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode() == KeyEvent.VK_SHIFT)
{
Recognizer recognizer = (Recognizer) cm.lookup("recognizer");
recognizer.deallocate();
}
这是我正在运行的主要课程:
public class HelloWorld extends MKeyListener implements KeyListener{
public static void main(String[] args) throws Exception {
JTextField textField = new JTextField();
textField.addKeyListener(new MKeyListener());
JFrame jframe = new JFrame();
jframe.add(textField);
jframe.setSize(400, 350);
jframe.setVisible(true);
if (args.length > 0) {
cm = new ConfigurationManager(args[0]);
} else {
cm = new ConfigurationManager(HelloWorld.class.getResource("helloworld.config.xml"));
}
}
我在这里做错了什么?