1. 程式人生 > >百度語音api的文字轉語音,語音轉文字-yellowcong

百度語音api的文字轉語音,語音轉文字-yellowcong

百度語言api的實現中,我發現坑爹了,文字轉語音很容易的就實現了,但是語言轉文字,就坑死了,我後來發現是音訊檔案的問題,mp3的檔案百度雲不支援,後來才搞明白,百度支援pcm的,需要將mp3的轉化為pcm格式的,在通過Base64加密,傳送到百度雲,發現坑爹死了,百度的語言識別不是特別的好,但是先有了單車,再考慮汽車吧。

專案原始碼

#原始碼存在於碼雲上
https://gitee.com/yellowcong/api/tree/master/yuyin

貯備知識

專案結構

這裡寫圖片描述

類說明

類名稱 作用
AudioClient 語音的主要類
Constants 常量,用來配置語音識別的引數
Audio2Text 語音轉文字的引數傳遞類
Text2Audio 文字轉語音的引數傳遞類
Result 識別後的結果類

實現程式碼

package com.yellowcong.baidu.yuyin;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.UUID;

import javax.xml.bind.DatatypeConverter;

import
com.yellowcong.baidu.utils.AudioUtils; import com.yellowcong.baidu.utils.Base64Utils; import com.yellowcong.baidu.utils.HttpClientUtils; import com.yellowcong.baidu.utils.JsonUtils; import com.yellowcong.baidu.utils.TrustAnyTrustManager; import com.yellowcong.baidu.yuyin.constant.Constants; import com.yellowcong.baidu.yuyin.model.Audio2Text; import
com.yellowcong.baidu.yuyin.model.Result; import com.yellowcong.baidu.yuyin.model.Text2Audio; /** * 建立日期:2018年1月14日<br/> * 建立時間:下午4:57:51<br/> * 建立者 :yellowcong<br/> * 機能概要: */ public class AudioClient { //"lhnN8uVsySG6SzdbEBSx2RwA"; //id private String appid ; // "V71cijc3Q9DZ5ZbFTd8sthFekDR3dTAC"; //金鑰 private String secret ; //使用者的token private String token ; public AudioClient(String appid, String secret) { super(); this.appid = appid; this.secret = secret; } public void setToken(String token) { this.token = token; } /** * 獲取Token * @return token */ public String getToken(){ String token = null; try { // String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id="+VoiceUtils.appid+"&client_secret="+VoiceUtils.secret; //獲取TOKEN的地址 String tokenUrl = String.format(Constants.TOKEN_URL, this.appid,this.secret); //傳送請求 String result = TrustAnyTrustManager.connect(tokenUrl); //獲取token token = JsonUtils.getMapper().readTree(result).get("access_token").asText(); //設定類的token this.token = token; } catch (Exception e) { e.printStackTrace(); } return token; } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午5:01:36<br/> * 建立使用者:yellowcong<br/> * 機能概要:將字串轉化為語音 * @param word 需要轉化為語音的文字 * @return 返回資料流 */ public InputStream text2Audio(String word){ Text2Audio word2Voice = new Text2Audio(); //設定轉化為檔案的字串 word2Voice.setTex(word); //呼叫 return this.text2Audio(word2Voice); } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午5:50:24<br/> * 建立使用者:yellowcong<br/> * 機能概要:將文字轉轉化為音訊 * @param word2Voice * @return */ public InputStream text2Audio(Text2Audio word2Voice){ //當token不存在的情況 if(this.isEmpty(this.token)){ this.token= this.getToken(); } //設定token word2Voice.setTok(this.token); //判斷是否有cuid if(this.isEmpty(word2Voice.getCuid())){ word2Voice.setCuid(UUID.randomUUID().toString()); } if(this.isEmpty(word2Voice.getLan())){ //預設的語言 word2Voice.setLan(Constants.DEFAULT_LAN); } if(this.isEmpty(word2Voice.getCtp())){ //訪問型別 word2Voice.setCtp(Constants.DEFAULT_CTP); } if(this.isEmpty(word2Voice.getPer())){ word2Voice.setPer(Constants.DEFAULT_PER); } //獲取返回的引數 String param = this.getParam(word2Voice); if(param == null || "".equals(param)){ return null; } //獲取連線誒地址 String url = Constants.TEXT_AUDIO_URL+"?"+param; //獲取語音資料 InputStream in= HttpClientUtils.downLoad(url); return in; } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午10:46:02<br/> * 建立使用者:yellowcong<br/> * 機能概要: 判斷是否為空 * @param str * @return */ private boolean isEmpty(String str){ if(str == null || str.trim().equals("")){ return true; } return false; } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午10:36:03<br/> * 建立使用者:yellowcong<br/> * 機能概要:將聲音轉化為 文字 * @param audioFile * @return */ public Result audio2Text(File audioFile){ Audio2Text parm = new Audio2Text(); //視屏格式 parm.setFormat("pcm"); //取樣率, 8000 或者 16000, 推薦 16000 採用率 parm.setRate(16000); //單通道 parm.setChannel(1); parm.setCuid(UUID.randomUUID().toString()); //當token不存在的情況 if(this.token == null || "".equals(this.token)){ this.token= this.getToken(); } parm.setToken(this.getToken()); File targertFile = audioFile; //當不是pcm檔案的時候 if(!audioFile.getName().endsWith("pcm")){ AudioUtils audio = AudioUtils.getInstance(); //將檔案轉化為 pcm檔案 File outPcmFile = new File(audioFile.getParentFile().getAbsolutePath()+File.pathSeparator+UUID.randomUUID().toString()+".pcm"); if(!audio.convertMP32Pcm(audioFile.getAbsolutePath(), outPcmFile.getAbsolutePath())){ return null; } targertFile = outPcmFile; } //加密音訊檔案 Base64Utils utils = Base64Utils.getInstance(); //讀取檔案basecode編碼 String mp3Base64Str = utils.file2Base64(targertFile); //讀取檔案大小 int len = utils.getFileSize(targertFile); parm.setLen(len); parm.setSpeech(mp3Base64Str); String json = JsonUtils.object2Json(parm); //傳送請求到伺服器 String jsonResult = HttpClientUtils.postJson(Constants.AUDIO_TEXT_URL, json); //刪除臨時檔案 if(!targertFile.getAbsolutePath().equals(audioFile.getAbsolutePath())){ targertFile.delete(); } System.out.println(jsonResult); Result result = JsonUtils.json2Object(jsonResult, Result.class); return result; } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午5:43:24<br/> * 建立使用者:yellowcong<br/> * 機能概要:獲取請求的引數 * @param voice * @return */ public String getParam(Text2Audio word2Voice) { String paramStr = null; try { Class<?> clazz = word2Voice.getClass(); Field [] fields = word2Voice.getClass().getDeclaredFields(); StringBuffer sb = new StringBuffer(); for(Field field:fields){ String fieldNm = field.getName(); //獲取方法名稱 String methodNm = this.getMethodName(field); //執行方法 Object obj = clazz.getMethod(methodNm).invoke(word2Voice); //當引數資料為空的情況,直接 if(obj != null && !"".equals(obj.toString())){ sb.append(fieldNm+"="+obj.toString()+"&"); } } if(sb.length() >0){ paramStr = sb.substring(0, sb.length()-1); } } catch (Exception e) { e.printStackTrace(); } return paramStr; } /** * 建立日期:2018年1月14日<br/> * 建立時間:下午5:35:44<br/> * 建立使用者:yellowcong<br/> * 機能概要:根據欄位的名稱來獲取get方法的名稱 * @param field 欄位 * @return */ private String getMethodName(Field field){ String fieldNm = field.getName(); String methodNm = "get"+fieldNm.substring(0, 1).toUpperCase()+fieldNm.substring(1); return methodNm; } }

測試程式碼

package yellowcong.yuyin;

import java.io.File;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.yellowcong.baidu.utils.AudioUtils;
import com.yellowcong.baidu.utils.FileUtils;
import com.yellowcong.baidu.yuyin.AudioClient;
import com.yellowcong.baidu.yuyin.model.Result;
import com.yellowcong.baidu.yuyin.model.Text2Audio;

/**
 * 建立日期:2018年1月14日<br/>
 * 建立時間:下午5:31:46<br/>
 * 建立者    :yellowcong<br/>
 * 機能概要:
 */
public class Demo {

    private AudioClient client = null;

    @Before
    public void setUp(){
        String appid = "lhnN8uVsySG6SzdbEBSx2RwA";
        String secret = "V71cijc3Q9DZ5ZbFTd8sthFekDR3dTAC";
        client = new AudioClient(appid,secret);

    }

    @Test
    public void testText2Audio(){

        InputStream in = client.text2Audio("把你撓吐露皮了");
        FileUtils.copyInputStreamToFile(in, new File("D:/xx.mp3"));
    }

    @Test
    public void test2Text2Audio(){
        Text2Audio word = new Text2Audio();
        word.setTex("王賤狗,著急了吧");
        //語音 0-4
        word.setPer("4");
        InputStream in = client.text2Audio(word);
        FileUtils.copyInputStreamToFile(in, new File("D:/xx.mp3"));
    }

    /**
     * 建立日期:2018年1月14日<br/>
     * 建立時間:下午10:52:00<br/>
     * 建立使用者:yellowcong<br/>
     * 機能概要:將音訊轉檔案
     * @throws Exception
     */
    @Test
    public void testAduio2Text() throws Exception{
        Text2Audio word = new Text2Audio();
        word.setTex("你是逗逼");
        InputStream in = client.text2Audio(word);
        final File outFile = new File("D:/test.mp3");
        FileUtils.copyInputStreamToFile(in, outFile);

        //開啟執行緒 ,播放音樂
        new Thread() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                //播放檔案
                try {
                    AudioUtils.getInstance().playMP3(outFile.getAbsolutePath());
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }.start();

        //轉義翻譯結果
        Result result = client.audio2Text(outFile);

        //列印翻譯的結果
        System.out.println(result.getResult()[0]);

    }

    /**
     * 建立日期:2018年1月14日<br/>
     * 建立時間:下午6:07:47<br/>
     * 建立使用者:yellowcong<br/>
     * 機能概要:測試token的獲取
     * @throws Exception
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws SecurityException
     */
    @Test
    public void testGetToken() throws Exception, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException{
        String token = client.getToken();
        Assert.assertNotNull(token);
    }

}

結果,語音轉化有時候挺好,有時候,就完犢子
這裡寫圖片描述