微信小程序实现语音识别

小程序实现语音识别功能,通过语音的方式代替手动输入查询。经过查询微信小程序api,发现微信并没有对外提供语音识别的api,所以要另外想办法。经过多发查找资料发现了思路。

解决思路:

微信小程序提供了录音的功能,通过录音的方式,然后把录音文件传到服务器,后台服务器将语音转码,然后再调用第三方语音识别api,我这里使用的是百度的api,最后在将识别的文字返回给微信小程序。

直接上代码:

小程序端代码:

startRecord: function() {

if (this.recorderManager == null) {

this.recorderManager = wx.getRecorderManager();

this.options = {

duration: 10000,

sampleRate: 16000,

numberOfChannels: 1,

encodeBitRate: 64000,

format: 'mp3',

frameSize: 50

}

}

this.recorderManager.start(this.options);

this.recorderManager.onStop((res) => {

console.log(res)

wx.uploadFile({

url: 'https://xxxx',//将录音文件传到后台服务器

filePath: res.tempFilePath,

method:'POST',

name: 'file',

header: {

'content-type': 'multipart/form-data'

},

success: function(res) {

console.log(res);

},

fail: function() {

console.log("语音识别失败");

}

})

});

},

stopRecord: function() {

this.recorderManager.stop()

}

服务端代码:

注意:需要使用mp3plugin.jar包,网上可以下载到。

    // 百度语音识别
    public static final String APP_ID = "xxx";
    public static final String API_KEY = "xxx";
    public static final String SECRET_KEY = "xxx";

    /**
     * @Description TODO
     * @return
     */
    @RequestMapping(value = "speechRecognition", method = RequestMethod.POST)
    @ResponseBody
    public Object speechReco(HttpServletRequest request) {
        MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
        try {
            byte[] pcmBytes = mp3Convertpcm(file.getInputStream());
            org.json.JSONObject resultJson = speechBdApi(pcmBytes);
            System.out.println(resultJson.toString());
            if (null != resultJson && resultJson.getInt("err_no") == 0) {
                return resultJson.getJSONArray("result").get(0).toString().split(",")[0];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @Description MP3转换pcm
     * @param mp3Stream
     *            原始文件流
     * @return 转换后的二进制
     * @throws Exception
     */
    public byte[] mp3Convertpcm(InputStream mp3Stream) throws Exception {
        // 原MP3文件转AudioInputStream
        BufferedInputStream zipTest=new BufferedInputStream(mp3Stream);
        //重新包装一层,不然会报错。
        AudioInputStream mp3audioStream = AudioSystem.getAudioInputStream(zipTest);
        // 将AudioInputStream MP3文件 转换为PCM AudioInputStream
        AudioInputStream pcmaudioStream = AudioSystem.getAudioInputStream(AudioFormat.Encoding.PCM_SIGNED,
                mp3audioStream);
        byte[] pcmBytes = IOUtils.toByteArray(pcmaudioStream);
        pcmaudioStream.close();
        mp3audioStream.close();
        return pcmBytes;
    }

    /**
     * @Description 调用百度语音识别API
     * @param pcmBytes
     * @return
     */
    public static org.json.JSONObject speechBdApi(byte[] pcmBytes) {
        // 初始化一个AipSpeech
        AipSpeech client = new AipSpeech(APP_ID, API_KEY, SECRET_KEY);
        // 可选:设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
        // 调用接口
        org.json.JSONObject res = client.asr(pcmBytes, "pcm", 16000, null);
        return res;
    }

猜你喜欢

转载自www.cnblogs.com/lanshu/p/11899102.html