注:在线语法识别服务已下线,新用户无法使用。

    1. //1.创建SpeechRecognizer对象
    2. SpeechRecognizer mAsr = SpeechRecognizer.createRecognizer( );
    3. // ABNF语法示例,可以说”北京到上海”
    4. String mCloudGrammar = "#ABNF 1.0 UTF-8;
    5. languagezh-CN;
    6. mode voice;
    7. root $main;
    8. $main = $place1 到$place2 ;
    9. $place1 = 北京 | 武汉 | 南京 | 天津 | 天京 | 东京;
    10. $place2 = 上海 | 合肥; ";
    11. //2.构建语法文件
    12. mAsr.setParameter(SpeechConstant.TEXT_ENCODING, "utf-8");
    13. ret = mAsr.buildGrammar("abnf", mCloudGrammar , grammarListener);
    14. if (ret != ErrorCode.SUCCESS){
    15. DebugLog.Log("语法构建失败,错误码:" + ret);
    16. }else{
    17. DebugLog.Log("语法构建成功");
    18. }
    19. //3.开始识别,设置引擎类型为云端
    20. mAsr.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
    21. //设置grammarId
    22. mAsr.setParameter(SpeechConstant.CLOUD_GRAMMAR, grammarId);
    23. mAsr.startListening(mRecognizerListener);
    24. if (ret != ErrorCode.SUCCESS) {
    25. DebugLog.Log("识别失败,错误码: " + ret);
    26. }
    27. //构建语法监听器
    28. private GrammarListener grammarListener = new GrammarListener() {
    29. @Override
    30. public void onBuildFinish(String grammarId, SpeechError error) {
    31. if(error == null && !TextUtils.isEmpty(grammarId) ){
    32. //构建语法成功,请保存grammarId用于识别
    33. }else{
    34. DebugLog.Log("语法构建失败,错误码:" + error.getErrorCode());
    35. }
    36. }
    37. };