企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 使用麦克风当音听写示例 ~~~ //1.创建SpeechRecognizer对象 SpeechRecognizer mIat= SpeechRecognizer.createRecognizer( ); //2.设置听写参数,详见《MSC Reference Manual》SpeechConstant类 mIat.setParameter(SpeechConstant.DOMAIN, "iat"); mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); mIat.setParameter(SpeechConstant.ACCENT, "mandarin "); //3.开始听写 mIat.startListening(mRecoListener); //听写监听器 private RecognizerListener mRecoListener = new RecognizerListener(){ //听写结果回调接口(返回Json格式结果,用户可参见附录); //一般情况下会通过onResults接口多次返回结果,完整的识别内容是多次结果的累加; //关于解析Json的代码可参见MscDemo中JsonParser类; //isLast等于true时会话结束。 public void onResult(RecognizerResult results, boolean isLast){ DebugLog.Log("Result:"+results.getResultString ()); } //会话发生错误回调接口 public void onError(SpeechError error) { error.getPlainDescription(true) //获取错误码描述 } //开始录音 public void onBeginOfSpeech() {} //音量值0~30 public void onVolumeChanged(int volume){} //结束录音 public void onEndOfSpeech() {} //扩展用接口 public void onEvent(int eventType,int arg1,int arg2,String msg) {} }; ~~~ ## 使用音频文件听写示例 ~~~ //1.创建SpeechRecognizer对象 SpeechRecognizer mIat= SpeechRecognizer.createRecognizer( ); //2.设置听写参数,详见《MSC Reference Manual》SpeechConstant类 mIat.setParameter(SpeechConstant.DOMAIN, "iat"); mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn"); mIat.setParameter (SpeechConstant.ACCENT, "mandarin "); mIat.setParameter(SpeechConstant.AUDIO_SOURCE, "-1"); //3.开始听写 mIat.startListening(mRecoListener); //voiceBuffer为音频数据流,splitBuffer为自定义分割接口,将其以4.8k字节分割成数组 ArrayList<byte[]> buffers = splitBuffer(voiceBuffer,voiceBuffer.length, 4800); for (int i = 0; i < buffers.size(); i++) { // 每次写入msc数据4.8K,相当150ms录音数据 mIat.writeAudio(buffers.get(i), 0, buffers.get(i).length); } mIat.stopListening(); //听写监听器 private RecognizerListener mRecoListener = new RecognizerListener(){ public void onResult(RecognizerResult results, boolean isLast) { DebugLog.Log("Result:"+results.getResultString ()); } //会话发生错误回调接口 public void onError(SpeechError error) { error.getPlainDescription(true) //获取错误码描述 } //开始录音 public void onBeginOfSpeech() {} //音量值0~30 public void onVolumeChange( int volume ) {} } ~~~ ## 上传用户词表 上传用户词表可以提高词表内词汇的识别率,也可以提高语义的效果,每个用户终端设备对应一个词表,用户词表的格式及构造方法详见[《MSC Reference Manual》](http://mscdoc.xfyun.cn/java/api)UserWords类。 ~~~ private void uploadUserWords() { SpeechRecognizer recognizer = SpeechRecognizer.getRecognizer(); UserWords userwords = new UserWords(USER_WORDS); recognizer.setParameter( SpeechConstant.DATA_TYPE, "userword" ); recognizer.updateLexicon("userwords", userwords.toString(), lexiconListener); } /** * 词表上传监听器 */ LexiconListener lexiconListener = new LexiconListener() { @Override public void onLexiconUpdated(String lexiconId, SpeechError error) { if (error == null) DebugLog.Log("*************上传成功*************"); else DebugLog.Log("*************" + error.getErrorCode()+ "*************"); } }; ~~~