使用百度api实现文本转语音功能

1.接口中调用,此处只截取部分内容,不包含整个完整接口
使用百度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]

你可能感兴趣的:(技术分享,java,语音识别)