前面我们已经运行过HelloWorld这个Demo了,今天我们简单分析一下它的流程。


1、创建ConfigurationManager对象,并传入一个xml的配置文件路径。整个Sphinx4都是采用配置文件的方式来管理对象之间的关系,有点类似Spring框架,这样做的最大好处就是灵活,如果你要改变某个对象的行为,只需修改一下配置文件即可,而不必修改源代码。


ConfigurationManager cm;


if (args.length > 0) {

           cm = newConfigurationManager(args[0]);

       } else {

           cm = newConfigurationManager(HelloWorld.class.getResource("helloworld.config.xml"));

       }

}


2、调用ConfigurationManager的lookup方法查找Recognizer这个组件,在配置文件中每个类都可以看做是一个Component,当然还有其他类型,如基本数据类型,ComponentList类型等


Recognizer recognizer = (Recognizer) cm.lookup("recognizer");



3、为Recognizer分配资源


recognizer.allocate();



4、查找麦克风Compnent,启动录音


Microphone microphone = (Microphone) cm.lookup("microphone");

if (!microphone.startRecording()) {

           System.out.println("Cannot start microphone.");

           recognizer.deallocate();

           System.exit(1);

       }

}


5、进入一个死循环,不停的调用 Recognizer的recognize方法获取识别的结果


while (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");

                       }

            }

     }


从上面的分析可以看出,整个的识别流程还是比较简单的。这里涉及到了两个重要的类,那就是

ConfigurationManager和Recognizer。ConfigurationManager封装了整个sphinx4的属性信息,xml文件的解析,对象的创建等等,可以说它是整个sphinx4的大总管。而Recognizer封装了识别相关的信息,如前段的处理,解码等等,Recognizer是实际做事的人,后面我们就以这两个类为切入点,一步一步分析它们内部的调用流程。