本文介绍了java中的语音识别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的项目中使用语音识别,我发现了这段代码,但是当我运行它时,我收到一个错误:
I want to use speech recognition in my project and I found this code but when I run it I get an error which is:
run: java.lang.NullPointerException
at newpackage.HelloWorld.main(HelloWorld.java:55)
请问你们其中一个人可以帮我解决这个问题吗?
Please could one of you help me in this problem?
这是我使用的服务器代码:
This is the server code that I use:
package newpackage;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.speech.*;
import javax.speech.recognition.*;
import java.io.FileReader;
import java.util.Locale;
public class HelloWorld extends ResultAdapter {
static Recognizer rec;
// Receives RESULT_ACCEPTED event: print it, clean up, exit
public void resultAccepted(ResultEvent e) {
Result r = (Result)(e.getSource());
ResultToken tokens[] = r.getBestTokens();
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i].getSpokenText() + " ");
System.out.println();
try {
// Deallocate the recognizer and exit
rec.deallocate();
} catch (EngineException ex) {
Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex);
} catch (EngineStateError ex) {
Logger.getLogger(HelloWorld.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
public static void main(String args[]) {
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
FileReader reader = new FileReader(args[0]);
RuleGrammar gram = rec.loadJSGF(reader);
gram.setEnabled(true);
// Add the listener to get results
rec.addResultListener(new HelloWorld());
// Commit the grammar
rec.commitChanges();
// Request focus and start listening
rec.requestFocus();
rec.resume();
} catch (Exception e) {
e.printStackTrace();
// System.out.println("the problem");
}
}
}
推荐答案
重写
// Create a recognizer that supports English.
rec = Central.createRecognizer(
new EngineModeDesc(Locale.ENGLISH));
如下所示
SynthesizerModeDesc desc = new SynthesizerModeDesc(
null, // engine name
"general", // mode name
Locale.US, // locale
null, // running
null); // voice
synth = Central.createSynthesizer(desc);
这篇关于java中的语音识别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!