java中的语音识别

5 java speech-recognition javax.speech

我想在我的项目中使用语音识别,我找到了这段代码,但是当我运行它时,我得到一个错误:

run: java.lang.NullPointerException
        at newpackage.HelloWorld.main(HelloWorld.java:55)
Run Code Online (Sandbox Code Playgroud)

请你们中的一个人能帮我解决这个问题吗?

这是我使用的服务器代码:

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");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

dus*_*ell 2

if (rec != null) {
    System.out.println(rec);
}
else {
    System.out.println("rec is null");   
    // <-- here's your problem.  you need to return, exit, or throw here!
}

// Start up the recognizer
rec.allocate();  // <-- This is the line that's blowing out (I assume)
Run Code Online (Sandbox Code Playgroud)

您将得到一个空指针,因为即使您的 else 正在处理recnull 时的情况,您的程序仍会继续。当为空时,您需要返回或退出,或者其他东西rec

注意:另外,我重新格式化了您的代码,因为很难阅读您的 if/else。如果您要在 if/else 的一个分支上使用花括号,则应该在两个分支上都使用花括号。它使它更具可读性。

编辑:哦,是的,至于为什么createRecognizer回来null,恐怕我不知道。