必要参数准备
AppId
API Key
Sercret
单例模式,启动时创建
单例
/**
* @author byChen
* @date 2021/9/30
*/
public class SingAipSpeech {
/**
* 将构造方法私有化,保证其他地方new不出来
*/
private SingAipSpeech(){}
/**
* 在内部使用静态修饰,new一个该对象,该对象就是唯一单例(私有化方法在内部可以使用)
*/
private static final AipSpeech one = new AipSpeech("24931065", "xGdXj7fzqlADUHrP2QULBap3", "ncqrNf6xdqLrjUAbVnZc5nqhvqA7VwWH");
/**
* 使用静态修饰,可以用方法名直接点出来方法,而不需要新建对象(实际上因为单例,也新建不出来)
* @return
*/
public static AipSpeech getAipSpeech(){
// 可选:设置网络连接参数
one.setConnectionTimeoutInMillis(2000);
one.setSocketTimeoutInMillis(60000);
return one;
}
}
启动创建
/**
* @author byChen
* @date 2021/9/30
*/
@Component
@Order(value = 1)
public class AipSpeechRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
AipSpeech aipSpeech = SingAipSpeech.getAipSpeech();
System.out.println("百度语音识别创建成功"+aipSpeech);
}
}
具体逻辑
/**
* 百度文字合成语音
*/
@GetMapping("/baiduSpeech")
public R baiduSpeech(@RequestParam("writing") String write) {
AipSpeech aipSpeech = SingAipSpeech.getAipSpeech();
// 设置可选参数
HashMap<String, Object> options = new HashMap<String, Object>();
//语速,取值0-9,默认为5中语速
options.put("spd", "5");
//音调,取值0-9,默认为5中语调
options.put("pit", "5");
//发音人选择, 0为女声,1为男声,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女
options.put("per", "0");
TtsResponse res = aipSpeech.synthesis(write, "zh", 1, options);
//生成的音频数据
byte[] data = res.getData();
String s = cn.hutool.core.lang.UUID.randomUUID().toString();
//byte数组保存到本地文件
String s1 = fileToBytes(data, "D:\\baiduYuYin\\", s + ".mp3");
return R.ok(s1);
}
tips: byte数组转换为本地文件
/**
* 将Byte数组转换成文件
*
* @param bytes byte数组
* @param filePath 文件路径 如 D://test/ 最后“/”结尾
* @param fileName 文件名
*/
public static String fileToBytes(byte[] bytes, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
String absolutePath = "";
try {
file = new File(filePath + fileName);
String name = file.getName();
absolutePath = file.getAbsolutePath();
System.out.println("文件名称" + name);
System.out.println("文件地址" + absolutePath);
if (!file.getParentFile().exists()) {
//文件夹不存在 生成
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return absolutePath;
}