1. 程式人生 > 其它 >使用百度api實現文字轉語音功能

使用百度api實現文字轉語音功能

1.介面中呼叫,此處只擷取部分內容,不包含整個完整介面
在這裡插入圖片描述
2.文字轉語音工具類

/**

  • 文字轉語音工具類
    */
    public class TextToAudio {

    //private final String filepath = “/fileupload”;

    public static void main(String[] args) throws IOException, DemoException {
    (new TextToAudio()).run("/upload", “我的名字叫一起隨緣”);
    }

    //填寫網頁上申請的appkey 如 $apiKey=“g8eBUMSokVB1BHGmgxxxxxx”

    private final String appKey = “申請的appkey”;//此處根據自己申請的appkey自行填寫

    // 填寫網頁上申請的APP SECRET 如 $secretKey=“94dc99566550d87f8fa8ece112xxxxx”//此處根據自己申請的APP SECRET自行填寫
    private final String secretKey = “申請的APP SECRET”;

    // 發音人選擇, 基礎音庫:0為度小美,1為度小宇,3為度逍遙,4為度丫丫,
    // 精品音庫:5為度小嬌,103為度米朵,106為度博文,110為度小童,111為度小萌,預設為度小美
    private final int per = 0;

    // 語速,取值0-15,預設為5中語速
    private final int spd = 5;
    // 音調,取值0-15,預設為5中語調
    private final int pit = 5;
    // 音量,取值0-9,預設為5中音量
    private final int vol = 5;

    // 下載的檔案格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
    private final int aue = 6;

    public final String url = “http://tsn.baidu.com/text2audio”; // 可以使用https

    private String cuid = “1234567JAVA”;

    public String run(String filepath, String text) throws IOException, DemoException {
    TokenHolder holder = new TokenHolder(appKey, secretKey, TokenHolder.ASR_SCOPE);
    holder.refresh();
    String token = holder.getToken();

     // 此處2次urlencode, 確保特殊字元被正確編碼
     String params = "tex=" + ConnUtil.urlEncode(ConnUtil.urlEncode(text));
     params += "&per=" + per;
     params += "&spd=" + spd;
     params += "&pit=" + pit;
     params += "&vol=" + vol;
     params += "&cuid=" + cuid;
     params += "&tok=" + token;
     params += "&aue=" + aue;
     params += "&lan=zh&ctp=1";
     System.out.println(url + "?" + params); // 反饋請帶上此url,瀏覽器上可以測試
     HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
     conn.setDoInput(true);
     conn.setDoOutput(true);
     conn.setConnectTimeout(5000);
     PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
     printWriter.write(params);
     printWriter.close();
     String contentType = conn.getContentType();
     
     if (contentType.contains("audio/")) {
         byte[] bytes = ConnUtil.getResponseBytes(conn);
         String format = getFormat(aue);
         FileNameGenerate fileNameGenerate = new FileNameGenerate();
         //String fileName = fileNameGenerate.getFileNameGenerate();
         //File file = new File(filepath,fileName + "." + format); // 開啟mp3檔案即可播放
         String fileName = fileNameGenerate.getFileNameGenerate()+ "." + format;
         File file = new File(filepath,fileName); // 開啟mp3檔案即可播放
         if (!file.exists()) {
         	file.getParentFile().mkdirs();
         }
         System.out.println(file.getAbsolutePath());
         FileOutputStream os = new FileOutputStream(file);
         os.write(bytes);
         os.close();
         System.out.println("audio file write to " + filepath + fileName);
         return filepath + fileName;
     } else {
         System.err.println("ERROR: content-type= " + contentType);
         String res = ConnUtil.getResponseString(conn);
         System.err.println(res);
         return "";
     }
    

    }

    // 下載的檔案格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
    private String getFormat(int aue) {
    String[] formats = {“mp3”, “pcm”, “pcm”, “wav”};
    return formats[aue - 3];
    }

}

3.用日期生成檔名工具類
package ****;//換成實際專案中的包

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**

  • 檔名生成工具類(根據日期生成檔名)
    */
    public class FileNameGenerate {

    private String valueOfString(String str, int len) {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < len - str.length(); i++) {
    sb.append(“0”);
    }
    return (sb.length() == 0) ? (str) : (sb.toString() + str);
    }

    public String getDateFormat(){
    SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
    return df.format(new Date());
    }

    public Date getDateFormat(String time){
    SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);
    try {
    return df.parse(time);
    } catch (ParseException e) {
    e.printStackTrace();
    }
    return null;
    }

    private String getFileNameGenerate(Calendar calendar) {
    StringBuffer sb = new StringBuffer();
    sb.append(String.valueOf(calendar.get(Calendar.YEAR)))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MONTH) + 1),2))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)),2))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)),2))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MINUTE)),2))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.SECOND)),2))
    .append(this.valueOfString(String.valueOf(calendar.get(Calendar.MILLISECOND)),3));
    return sb.toString();
    }

    public String getFileNameGenerate(String time){
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(this.getDateFormat(time));
    return this.getFileNameGenerate(calendar);
    }

    public String getFileNameGenerate(){
    Calendar calendar = new GregorianCalendar();
    return this.getFileNameGenerate(calendar);
    }

    public static void main(String[] args) {
    FileNameGenerate fileName = new FileNameGenerate();
    System.out.println(fileName.getFileNameGenerate());
    System.out.println(fileName.getFileNameGenerate(“2015-4-30 8:51:52”));
    }

}

注:
程式碼中依賴的工具類請參考我的資源:語文轉語音工具基礎類
連結:
語文轉語音工具基礎類
[https://download.csdn.net/download/qq_34279303/15513651]