前言:在开发中遇到将文字转换成语音的功能,并保存在本地,具体如何实现,请看下方代码实现
百度AI语音合成文档链接:http://ai.baidu.com/docs#/TTS-API/top
一、工具类的编写
public class YyhcUtils {
// 填写网页上申请的appkey
private static final String appKey = "";
// 填写网页上申请的APP SECRET
private static final String secretKey = "";
// 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声
private static final int per = 0;
// 语速,取值0-15,默认为5中语速
private static final int spd = 5;
// 音调,取值0-15,默认为5中语调
private static final int pit = 5;
// 音量,取值0-9,默认为5中音量
private static final int vol = 5;
// 下载的文件格式, 3:mp3(default) 4: pcm-16k 5: pcm-8k 6. wav
private static final int aue = 3;
public static final String url = "http://tsn.baidu.com/text2audio"; // 可以使用https
private static String cuid = "1234567JAVA";
private static String mPath = Constant.DICTIONARY;//文件路径
public static boolean run(String text, int per) throws IOException, DemoException, JSONException {
String token = "";//根据AK和SK获取token 具体可参考我之前文章:基于百度AI--理解与交互技术UNIT,实现聊天机器人 :https://blog.csdn.net/Abner_Crazy/article/details/88555084
// 此处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);
mPath = DICTIONARY + System.currentTimeMillis() + ".mp3";
File file = new File(mPath); // 打开mp3文件即可播放
FileOutputStream os = new FileOutputStream(file);
os.write(bytes);
os.close();
System.out.println("audio file write to " + file.getAbsolutePath());
return true;
} else {
System.err.println("ERROR: content-type= " + contentType);
String res = ConnUtil.getResponseString(conn);
System.err.println(res);
return false;
}
}
public static String getPath() {
return mPath;
}
}
二、调用:
如果是在Android 中调用,需要在子线程中调用:具体可参考如下例子:
new Thread(new Runnable() {
@Override
public void run() {
try {
boolean run = YyhcUtils.run(mEt_content.getText().toString(), per);
if (run) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mTv_path.setVisibility(View.VISIBLE);
mTv_path.setText("文件路径:" + YyhcUtils.getPath() + "目录下的MP3文件");
hidePross();
showBaseToast("合成完成");
}
});
} else {
showBaseToast("语音合成文件生成失败,请重试...");
}
} catch (Exception e) {
e.printStackTrace();
showBaseToast("语音合成失败,请重试...");
}
}
}).start();