我在使用 Java 的 Sphinx 语音识别库时遇到问题。我正在使用它来获取输入并处理它。我第一次得到输入时,它起作用了。第二次,它在我有机会说话之前立即回答。在那之后,它只是继续回答自己。我尝试在每次输入之前分配并在每次输入之后取消分配,但这似乎不起作用。我能做些什么?
代码:
这是处理获取输入的方法:
public void getInput() {
if (using) return;
using = true;
if (!allocated) {
JTalk.speak("Please hold.");
recognizer.allocate();
allocated = true;
}
JTalk.speak("Speak now.");
Result result = recognizer.recognize();
if (result != null) {
String resultText = result.getBestFinalResultNoFiller();
JDispatcher.getInstance().matchInput(resultText);
}
else {
JTalk.speak("Try again.");
}
using = false;
}
你需要知道的:
- 这是从 a
MouseListener
for a调用的TrayIcon
。 speak(String)
从.say <text>
_Runtime
matchInput(String)
遍历数组中所有已注册的侦听器并测试匹配。
更新 2:
根据 Nikolay Shmyrev 的回答,我尝试在构造函数中分配麦克风,并在getInput()
.
这是 SphinxBridge 类:
public class SphinxBridge {
private ConfigurationManager cm;
private Recognizer recognizer;
private Microphone microphone;
private boolean using = false;
public SphinxBridge() {
this.cm = new ConfigurationManager(SphinxBridge.class.getResource("input.config.xml"));
this.recognizer = (Recognizer) cm.lookup("recognizer");
this.microphone = (Microphone) cm.lookup("microphone");
recognizer.allocate();
}
public void getInput() {
if (using) return;
using = true;
if (!microphone.startRecording()) {
JTalk.speak("Cannot start microphone.");
return;
}
JTalk.speak("Speak now.");
Result result = recognizer.recognize();
if (result != null) {
String resultText = result.getBestFinalResultNoFiller();
JDispatcher.getInstance().matchInput(resultText);
}
else {
JTalk.speak("Try again.");
}
microphone.stopRecording();
using = false;
}
}
但是,这仍然行不通。首先,它工作正常。然而,对于随后的所有时间,它同时表示Speak now
和Try again
。
解决方案:
从上面的代码中,我简单地添加了
microphone.clear();
在开始录制的行上方。