Commit b3d69a48 by 苗权威

change

parent 15d47443
......@@ -20,6 +20,24 @@ import java.util.zip.*;
@Slf4j
public class FileUtil {
public static List<Path> getThePathAllMp3File(String dir) {
List<Path> result = new ArrayList<>();
getAllMp3Path(Paths.get(dir), result);
return result;
}
private static void getAllMp3Path(Path path, final List<Path> result) {
if (Files.isDirectory(path)) {
try {
Files.list(path).forEach(path1 -> getAllMp3Path(path1, result));
} catch (Exception e) {
log.error("FileUtil递归获取mp3 path fail:"+e);
}
} else if (StringUtils.endsWithAny(path.getFileName().toString(), ".mp3")){
result.add(path);
}
}
private static void getRecursion(Path path, final List<Path> result) {
if (Files.isDirectory(path)) {
try {
......
......@@ -554,6 +554,23 @@ public class TTSUtils {
return filename;
}
public static Boolean changeAudioConfigAddSilence(Integer sampleRate, String bitRate, String targetPath) {
try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
if ("1".equals(CallPython.ffmpegExecute(new StringBuilder("ffmpeg -i ").append(targetPath)
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3")
.append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar ").append(sampleRate)
.append(" -b:a ").append(bitRate)
.append(" -y ").append(temp).toString()))) {
Files.move(new File(temp).toPath(), new File(targetPath).toPath(), StandardCopyOption.REPLACE_EXISTING);
return true;
}
} catch (Exception e) {
log.error("changeAudioConfig 修改音频数据出错:sampleRate:{}, bitRate:{}, targetPath:{}, {}", sampleRate, bitRate, targetPath, e);
}
return false;
}
public static Boolean changeAudioConfig(Integer sampleRate, String bitRate, String targetPath) {
try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
......@@ -570,6 +587,7 @@ public class TTSUtils {
/**
* 合并mp3文件
* sox -n -r 48000 silence.wav trim 0.0 0.250
* @param filePathList 待合并mp3文件列表
* @param targetFilepath 合并文件地址
* @throws IOException
......@@ -596,11 +614,14 @@ public class TTSUtils {
} else {
if (xiaoai) {
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
for (int i = 0; i < filePathList.size(); i++) {
StringBuilder builder = new StringBuilder("ffmpeg ")
.append(StringUtils.join(str, " -i " + Initialize.getAudioDir() + "/silence/300ms.mp3" + " "))
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3")
.append(" -filter_complex ");
for (int i = 0; i < filePathList.size()*2; i++) {
builder.append("[").append(i).append(":a:0]");
}
builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append(targetFilepath);
builder.append("concat=n=").append(filePathList.size()*2).append(":v=0:a=1[a] -map [a] -b:a 64k -y ").append(targetFilepath);
CallPython.ffmpegExecute(builder.toString());
} else {
buildSoxCutAndCombine(filePathList, targetFilepath);
......@@ -682,11 +703,13 @@ public class TTSUtils {
// long temp;
// log.warn("sox 切除静音耗时:"+((temp=System.currentTimeMillis())-startMark));
List<String> str = cutedPaths.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
for (int k = 0; k < filePathList.size(); k++) {
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " "))
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3")
.append(" -filter_complex ");
for (int k = 0; k < filePathList.size()+1; k++) {
builder.append("[").append(k).append(":a:0]");
}
builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] -b:a 64k -y ").append(targetFilepath);
builder.append("concat=n=").append(filePathList.size()+1).append(":v=0:a=1[a] -map [a] -b:a 64k -y ").append(targetFilepath);
CallPython.ffmpegExecute(builder.toString());
// log.warn("ffmpeg 拼接耗时:"+(System.currentTimeMillis()-temp));
POOL.submit(() -> {
......@@ -848,5 +871,22 @@ public class TTSUtils {
// System.out.println(builder.toString());
// System.out.println(buildMP3Filename("苹果"));
// System.out.println(buildMP3Filename("没有了哦,换其他的水果"));
// List<String> filePathList = new ArrayList<>();
// filePathList.add("1.mp3");
// filePathList.add("2.mp3");
// List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
// StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
// for (int i = 0; i < filePathList.size(); i++) {
// builder.append("[").append(i).append(":a:0]");
// }
// builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] ").append("target.mp3");
// System.out.println(builder.toString());
// ffmpeg -i 1.mp3 -i 2.mp3 -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] target.mp3
System.out.println(TTSUtils.buildMP3Filename("你的建议很对,听了你的建议,兔子爸爸急忙把兔妈妈送到了啄木鸟医生开的诊所。"));
System.out.println(TTSUtils.buildMP3Filename("啄木鸟医生经过一番检查后,对兔子爸爸说:"));
System.out.println(TTSUtils.buildMP3Filename("你夫人的肚子里还有一个宝宝。他太淘气,躲在妈妈的肚子里不肯出来,在里面拳打脚踢呢。看来只能做手术了。"));
System.out.println(TTSUtils.buildMP3Filename("兔子妈妈一听,又吓得开始哇啦哇啦大叫。你可以安慰她一下吗?"));
}
}
......@@ -216,7 +216,7 @@ public class DeployController {
case 48000 : sampleRate = 48000;break;
default: sampleRate = 44100;
}
if (!TTSUtils.changeAudioConfig(sampleRate, bitRate, Initialize.AUDIO_DIR+path)) {
if (!TTSUtils.changeAudioConfigAddSilence(sampleRate, bitRate, Initialize.AUDIO_DIR+path)) {
return ServerResponse.createByErrorCodeMessage(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "修改音频采样率/比特率数据失败");
}
......@@ -348,6 +348,9 @@ public class DeployController {
}
log.error("耗时:"+(System.currentTimeMillis()-startTime));
toChannel.close();
if (StringUtils.isNotBlank(botAccount)) {
FileUtil.deleteFile(new File(Initialize.getAudioDir()+File.separator+botAccount));
}
if ("audio".equals(targetDir)) FileUtil.deleteFile(new File(targetDir));
Files.createDirectories(Paths.get(targetDir));
FileUtil.decompress(tempSliceName+".zip", targetDir);
......
......@@ -321,7 +321,11 @@ public class TTSController {
@PutMapping("/api/record/volume")
public ServerResponse changeRecordVolume(@RequestBody ChangeRecordVolume volume) {
return ttService.changeRecoedVolume(volume);
ServerResponse response = ttService.changeRecoedVolume(volume);
if (ResponseCode.SUCCESS.getCode().equals(response.getCode())) {
FileUtil.deleteFile(new File(StringUtils.join(new String[]{Initialize.getAudioDir(), volume.getBotName(), "xiaoai"},File.separator)));
}
return response;
}
// @GetMapping("/api/del/all/up")
......@@ -717,7 +721,8 @@ public class TTSController {
// String str = sendGet("http://cdntest.heyqiwu.cn/api/audio/cache/miaoTestTime/?filename=/miaoTestTime/A13/%E6%AD%A3%E5%B8%B8/e48e57b1f0a1f1a78fb7492e4654c727.mp3");
// System.out.println(str);
// System.out.println(TTSUtils.buildMP3Filename("为所有人类的共同命运。这对他们的言论自由权起到限制。"));
System.out.println(TTSUtils.buildMP3Filename("好了,我先问你个问题热热身吧。"));
System.out.println(TTSUtils.buildMP3Filename("兔妈妈和兔爸爸有了这么多兔宝宝,他们首先应该做什么呢?"));
}
}
......@@ -446,7 +446,7 @@ public class Initialize implements InitializingBean {
return SERVER_URL;
}
static String getAudioDir() {
public static String getAudioDir() {
return AUDIO_DIR;
}
......
......@@ -31,7 +31,7 @@ public class LieHuSchedule {
// private static final HashMap<String, String> LIE_HU_TOKEN_HEADER;
private static String LIE_HU_TOKEN;
public static volatile NlsClient nlsClient = new NlsClient("dd5b063d26014dde807dee21368d1478");
public static volatile NlsClient nlsClient = new NlsClient("26cd4e5cfb6445a9bbf107b3896f573d");
private static volatile AccessToken accessToken;
static {
......@@ -45,7 +45,7 @@ public class LieHuSchedule {
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
// @Scheduled(fixedDelay = 3600000, initialDelay = 3600000)
// @Scheduled(fixedDelay = 3600000, initialDelay = 36000000)
@Scheduled(fixedDelay = 3600000)
public void scheduleALiTTSToken() {
if (accessToken == null) {
......
......@@ -127,7 +127,7 @@ public class TTService {
final AtomicInteger hasRecord = new AtomicInteger();
// 过滤掉record目录
File[] needDelete = deleteBotDir.listFiles((dir, name) -> {
if (StringUtils.equalsAny(name, Initialize.getUploadedDir(), "Liehu1") || name.startsWith("Baidu")) {
if (StringUtils.startsWithAny(name, Initialize.getUploadedDir(), "Baidu", "Liehu", "Tencent", "ProTencent", "XunFei", "Alyun")) {
hasRecord.set(1);
return false;
}
......@@ -1529,10 +1529,11 @@ public class TTService {
}
});
}
return ServerResponse.createBySuccess();
} catch (Exception e) {
log.error("changeRecoedVolume error:{}, recordVolume:{}",e, recordVolume);
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
}
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
} else {
String path = StringUtils.join(new String[]{Initialize.getAudioDir(), recordVolume.getBotName(),
Initialize.getUploadedDir(), recordVolume.getNpcName(), TTSUtils.buildMP3Filename(recordVolume.getText())},File.separator);
......@@ -1543,13 +1544,13 @@ public class TTService {
try {
CallPython.soxiGetAudioConfig(command + path + " " + tempPath);
Files.move(Paths.get(tempPath), Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
return ServerResponse.createBySuccess();
} catch (Exception e) {
log.error("changeRecoedVolume move:{}, path:{}", e, path);
new File(tempPath).delete();
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
}
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
}
return ServerResponse.createBySuccess();
}
public ServerResponse getOneSenAudioConfig(String botName, String npcName, String text, String onlyCheckExist) {
......@@ -1688,7 +1689,7 @@ public class TTService {
case 48000 : sampleRate = 48000;break;
default: sampleRate = 44100;
}
if (!TTSUtils.changeAudioConfig(sampleRate, bitRate, filename)) {
if (!TTSUtils.changeAudioConfigAddSilence(sampleRate, bitRate, filename)) {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(500, "修改音频采样率/比特率数据失败"), 500);
return;
}
......@@ -1716,6 +1717,7 @@ public class TTService {
msg = "post record_callback_url error";
log.error("post record_callback_url error:{}",ExceptionUtils.getStackTrace(e));
}
FileUtil.deleteFile(new File(StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), "xiaoai"},File.separator)));
TTServiceUtil.buildUploadResponse(response, new TTSResponse(200,msg), 200);
}
......@@ -2080,7 +2082,7 @@ public class TTService {
needDeleteB64File.add(usFilename + ".b64");
try {
Files.copy(new File(fileInPackage).toPath(), usFile.toPath());
if (TTSUtils.changeAudioConfig(sampleRate, bitRate, usFilename)) {
if (TTSUtils.changeAudioConfigAddSilence(sampleRate, bitRate, usFilename)) {
boolean bn = successUpLoadFileIds.add(record.get(0));
if (!bn) noeTextSameId++;
} else {
......@@ -2186,6 +2188,7 @@ public class TTService {
// log.error("打包上传回调出现错误:{}",ExceptionUtils.getStackTrace(e));
// }
// });
int sum = successUpLoadFileIds.size()+repeate+noeTextSameId+empty;
try {
successUpLoadFileIds = successUpLoadFileIds.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
log.info("打包上传成功id个数:{}",successUpLoadFileIds.size());
......@@ -2209,13 +2212,15 @@ public class TTService {
return zipFolder;
}
POOL.submit(() -> {
FileUtil.deleteFile(new File(StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), "xiaoai"},File.separator)));
TTSUtils.deleteFile(new File(zipFolder));
for (String path: needDeleteB64File) {
TTSUtils.deleteFile(path);
}
// String recordPath = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), Initialize.getUploadedDir()},File.separator);
// List<Path> pts = FileUtil.getThePathAllMp3File(recordPath);
});
//log.info("msg:{}",msg);
int sum = successUpLoadFileIds.size()+repeate+noeTextSameId+empty;
if (failList.size() == 0) {
if (sum == all) {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, "全部成功"), 200);
......
......@@ -1533,13 +1533,25 @@ public class TTServiceEdition2 {
// System.out.println(TTSUtils.buildMP3Filename("天"));
// System.out.println(TTSUtils.buildMP3Filename("{晴天}还是{阴天}"));
String text = "我要买\uD83C\uDD70水果\uD83C\uDD71,\uD83C\uDD70青菜\uD83C\uDD71";
List<String> splitList = new ArrayList<>();
String[] arr = text.split("\uD83C\uDD70");
for (String item: arr) {
splitList.addAll(Arrays.asList(item.split("\uD83C\uDD71")));
}
splitList = splitList.stream().filter(s -> StringUtils.isNotBlank(s.replaceAll("\\p{P}", ""))).collect(Collectors.toList());
System.out.println(splitList);
// List<String> filePathList = new ArrayList<>();
// filePathList.add("1.mp3");
// filePathList.add("2.mp3");
// filePathList.add("3.mp3");
// List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
// StringBuilder builder = new StringBuilder("ffmpeg ")
// .append(StringUtils.join(str, " -i " + "/root" + "/silence/450ms.mp3" + " "))
// .append(" -i ").append("/root").append("/silence/250ms.mp3")
// .append(" -filter_complex ");
// for (int i = 0; i < filePathList.size()*2; i++) {
// builder.append("[").append(i).append(":a:0]");
// }
// builder.append("concat=n=").append(filePathList.size()*2).append(":v=0:a=1[a] -map [a] ").append("out.mp3");
// System.out.println(builder);
System.out.println(new StringBuilder("ffmpeg -i ").append("1.mp3")
.append(" -i ").append("/root").append("/silence/250ms.mp3")
.append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar ").append("44100")
.append(" -b:a ").append("64k")
.append(" -y ").append("2.mp3").toString());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment