使用讯飞SDK实现语音搜索功能

昨天刚刚结束了谷歌师资培训。在准备的近三天中也学到很多东西。电子档的材料都上传到了git上,但是还有手写的技术实现不想拍照上传。所以还是写篇文章记录一下,也算是巩固了。就按照我讲的顺序来写。
先总体,再细节(我喜欢这种逻辑,更容易理解把握)。
1.总体部分[IatController.java]:
前端获取到录音文件并转为base64编码交给后端进行处理。IatController层把base64编码转换为text文本。再对得到的文本进行分词处理[findWithWordDivision()],获取到关键词并将关键词保存到sentenceList中,再将sentenceList放入data数据中进行数据库查询。

@PostMapping(value = "/searchBySdkBase", produces = "application/json;charset=UTF-8")
    public Map<String,Object> searchBySdkBase(String base64){
        Map <String,Object> map=new HashMap<String, Object>();
        base64=base64.replace(" ","+");//用空格代替+
        try {
            String text = this.iatService.useIatSdkBase(base64);
            List<Sentence> sentenceList=new ArrayList<Sentence>();
            if(text.equals("") || text == null){
                map.put("info","error");
                return map;
            }
            sentenceList=this.sentenceService.findWithWordDivision(text);
            if(sentenceList == null || sentenceList.size() == 0){
                map.put("info","no sentence");
                return map;
            }
            map.put("info","success");
            map.put("data",sentenceList);
            return map;
        }
        catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

2.细节实现:
(1)在UploadUtils.java文件中:
后端将得到的base64编码通过方法uploadFileBase()变成字节数组byte [] buffer,并写入随机生成的文件中(也就是recordPath:.wav/.mp3格式文件)。然后创建.pcm格式文件路径(只是创建路径。先建个房子,再把居民塞进去)。最后返回recordPath+pcmPath(接下来会用,需要注意)。

public static String uploadFileBase(String base64,String upload,String recordPath,String pcmPath){
        
        String newFileName=UUID.randomUUID()+".wav";//避免重名:随机生成ID
        byte [] buffer=Base64.decodeBase64(base64);
        File file=new File(upload,newFileName);
        FileOutputStream fileOutputStream=null;
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
        }
        catch (IOException e){
            e.printStackTrace();
            return null;
        }
        try {
            System.out.println("file:"+file.getAbsolutePath());
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(buffer);
            //fileOutputStream.flush();
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e2){
            e2.printStackTrace();
        }
        finally {
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
        }
        recordPath="/root/uploadRecord/"+newFileName;
        if(recordPath.indexOf(".wav") > 0) {
            pcmPath = recordPath.substring(0, recordPath.indexOf("wav")) + "pcm";
        }
        else if(recordPath.indexOf(".mp3") > 0){
            pcmPath = recordPath.substring(0, recordPath.indexOf("mp3")) + "pcm";
        }
        System.out.println("rec"+recordPath);
        System.out.println("pcm"+pcmPath);
        transferWavToPcm(recordPath,pcmPath,upload);
        return recordPath+" "+pcmPath;
    }

通过transferWavToPcm()方法,将recordPath路径下的内容转为.pcm格式的内容,并放入刚刚创建好的pcmPath里(啥样人住啥样房子)。也就是说,我们成功获得了.pcm格式的文件,符合了讯飞SDK的要求,可以使用讯飞SDK了。

public static void transferWavToPcm(String recordPath,String pcmPath,String upload){
        String ffmpegPath="/usr/local/ffmpeg/bin/";
        String command=new File(ffmpegPath).getAbsolutePath()+"/ffmpeg -y -i "+recordPath+" -acodec pcm_s16le -f s16le -ac 1 -ar 16000 "+pcmPath;
        Runtime run=Runtime.getRuntime();
        try {
            Process p = run.exec(command);
            //
            p.getOutputStream().close();
            p.getInputStream().close();
            p.getErrorStream().close();
            p.waitFor();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        finally{
            run.freeMemory();
        }
    }

(2)IatUtils.java文件:
使用讯飞SDK将.pcm格式文件里的内容转为在上面第一大点里的text。
uploadFileBase()方法中:首先将UploadUtils.java文件中返回recordPath+pcmPath通过split()方法拆分了,拆出我们要的pcmPath。接着,讯飞SDK开始工作(开始监听),利用管道FileChannel获得路径为pcmPath的文件里的内容,并将获得到的内容放入到byteBuffer中,再将byteBuffer里的内容倒入字节数组byte[] buffer中(其实这个地方应该只写buffer的,但是我就是喜欢这样写,不规范但对我来说很清晰)(可以想象本来要把水倒入到蓝瓶子中,但是我先把水倒入到红瓶子中,再把红瓶子里的水倒入到蓝瓶子中。但是我还不懂为什么要这样,这也是我在上一篇文章中写的觉得Java麻烦的地方)。

public String RecoginzePcmFileBase(String base) throws IOException, InterruptedException {
        
        curResult=new StringBuilder();//当前结果
        String upload="/root/uploadRecord/";
        String recordPath="";
        String pcmPath="";
        String np="";

        if(recognizer == null){
            recognizer=SpeechRecognizer.createRecognizer();
            recognizer.setParameter(SpeechConstant.AUDIO_SOURCE,"-1");
            recognizer.setParameter(SpeechConstant.RESULT_TYPE,"json");
        }
        /**
         * wav,mp3 transfer to pcm
         */
        np = UploadUtils.uploadFileBase(base,upload,recordPath,pcmPath);//upload:文件在服务器中的位置 np=recorfPath+pcmPath
        if(np != null) {
            //拆分recordPath+pcmPath
            recordPath = np.split(" ")[0];
            pcmPath = np.split(" ")[1];
        }

        recognizer.startListening(recListener);//开始监听
        FileChannel fc = null;
        if(! pcmPath.equals("")) {
            fc = new RandomAccessFile(pcmPath, "r").getChannel();
        }
        MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()).load();
        System.out.println(byteBuffer.isLoaded());
        byte[] buffer = new byte[(int) fc.size()];

        if (byteBuffer.remaining() > 0) {
            byteBuffer.get(buffer, 0, byteBuffer.remaining());
        }

        if(buffer == null || buffer.length == 0){
            logger.error("no audio available");
            recognizer.cancel();
        }
        else{
            int len=buffer.length;
            recognizer.writeAudio(buffer,0,len);
            recognizer.stopListening();
            synchronized (lock){
                lock.wait();//主线程等待
            }
            //curResult.toString();
            File wav=new File(recordPath);
            File file2=new File(pcmPath);
            if(wav.exists()){
                wav.delete();
            }
            if(file2.exists()){
                file2.delete();
            }
            return getString(curResult.toString());
        }
        return null;
    }

结束监听。监听结果部分的recognizerResult是一个封装了JSON字符串的Java类。然后调用getResultString()方法获得JSON字符串:jsonStr。

//监听器工作
    private RecognizerListener recListener=new RecognizerListener() {
        @Override
        public void onVolumeChanged(int i) {
            logger.info("onVolumeChange enter");
        }

        @Override
        public void onBeginOfSpeech() {
            logger.info("onEndOfSpeech enter");
        }

        @Override
        public void onEndOfSpeech() {
            logger.info("onEndOfSpeech enter");
        }

        @Override
        public void onResult(RecognizerResult recognizerResult, boolean b) {
            logger.info("onResult enter");
            String jsonStr=recognizerResult.getResultString();
            curResult.append(jsonStr);
            if(b){
                synchronized (lock){
                    lock.notify();
                }
            }
        }

        //打印出报错信息
        @Override
        public void onError(SpeechError speechError) {
            logger.info("onError enter");
            if(null != speechError){
                logger.error("onError code:"+speechError.getErrorCode()+","+ speechError.getErrorDescription(true));
            }
        }

        @Override
        public void onEvent(int i, int i1, int i2, String s) {
            logger.info("onEvent enter");
        }
    };

那么我们最后的任务就是把这个jsonStr转为目标:text(也就是str)。
而把jsonStr转为str的第一步,居然是先把jsonStr再变回JSON(上一篇就吐槽了这个地方)。变回一个JSON对象。
因为jsonStr相当于把JSON数据打上了引号,而我们为了获取JSON中的数据,必须先把引号去掉,再拿里面的数据(key:value)。
将key为“ws”的“value”放在一个数组wsArr中,但key为“ws”的value也是一个key:value数组,所以只能再剥一层,直到剥出我们需要的value值,也就是wStr,也就是我们需要的text。//此处应该查阅讯飞官方文档https://www.xfyun.cn/doc/asr/voicedictation/Java-SDK.html

//{"sn":1,"ls":true,"bg":0,"ed":0,"ws":[{"bg":0,"cw":[{"w":"今天","sc":0}]},
    //jsonStr转换为str
    public String getString(String jsonStr){
        StringBuffer stringBuffer=new StringBuffer("");
        JSONObject jsonObject=JSON.parseObject(jsonStr);//转成JSON对象

        JSONArray wsArr=jsonObject.getJSONArray("ws");//ws:word sentence
        for(int i=0;i<wsArr.size();i++) {
            JSONObject wsArrObj=wsArr.getJSONObject(i);
            JSONArray CWArr=wsArrObj.getJSONArray("cw");//cw:Chinese word
            for (int j = 0; j < CWArr.size(); j++) {
                JSONObject CWArrObj = CWArr.getJSONObject(j);
                String wStr = CWArrObj.getString("w");//w:word
                stringBuffer.append(wStr);
                str.add(wStr);
            }
        }
        return stringBuffer.toString();
    }

    public List<String> getStr() {
        return str;
    }

}

注:2.(2)部分的三个片段代码加在一起才是完整的。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容