Commit d96bf9ea by 苗权威

0113

parent 41eb7a56
...@@ -190,7 +190,7 @@ ...@@ -190,7 +190,7 @@
### 获取音频文件 ### 获取音频文件
#### Request #### Request
- URL:```/api/tts/get_audio``` - URL:```/api/audio/cache/{botAccount}/```
- METHOD:**GET** - METHOD:**GET**
- URL Parameters: - URL Parameters:
......
...@@ -554,22 +554,29 @@ public class TTSUtils { ...@@ -554,22 +554,29 @@ public class TTSUtils {
return filename; return filename;
} }
public static Boolean addAudioSlice(String targetPath) { // public static Boolean addAudioSlice(String targetPath) {
try { // try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3"; // String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
if ("1".equals(CallPython.ffmpegExecute(new StringBuilder("ffmpeg -i ").append(targetPath) // if ("1".equals(CallPython.ffmpegExecute(new StringBuilder("ffmpeg -i ").append(targetPath)
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3") // .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 44100 -b:a 64k") // .append(" -filter_complex [0:a:0][1:a:0]concat=n=2:v=0:a=1[a] -map [a] -ar 44100 -b:a 64k")
.append(" -y ").append(temp).toString()))) { // .append(" -y ").append(temp).toString()))) {
Files.move(new File(temp).toPath(), new File(targetPath).toPath(), StandardCopyOption.REPLACE_EXISTING); // Files.move(new File(temp).toPath(), new File(targetPath).toPath(), StandardCopyOption.REPLACE_EXISTING);
return true; // return true;
} // }
} catch (Exception e) { // } catch (Exception e) {
log.error("changeAudioConfig 修改音频数据出错:targetPath:{}, {}", targetPath, e); // log.error("changeAudioConfig 修改音频数据出错:targetPath:{}, {}", targetPath, e);
} // }
return false; // return false;
} // }
/**
* 改变音频比特率和采样率参数并在开头增加250ms的静默音
* @param sampleRate
* @param bitRate
* @param targetPath
* @return
*/
public static Boolean changeAudioConfigAddSilence(Integer sampleRate, String bitRate, String targetPath) { public static Boolean changeAudioConfigAddSilence(Integer sampleRate, String bitRate, String targetPath) {
try { try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3"; String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
...@@ -587,6 +594,13 @@ public class TTSUtils { ...@@ -587,6 +594,13 @@ public class TTSUtils {
return false; return false;
} }
/**
* 改变音频比特率和采样率参数
* @param sampleRate 采样率
* @param bitRate 比特率
* @param targetPath 目标地址
* @return
*/
public static Boolean changeAudioConfig(Integer sampleRate, String bitRate, String targetPath) { public static Boolean changeAudioConfig(Integer sampleRate, String bitRate, String targetPath) {
try { try {
String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3"; String temp = targetPath.substring(0, targetPath.lastIndexOf("."))+"_.mp3";
...@@ -602,10 +616,10 @@ public class TTSUtils { ...@@ -602,10 +616,10 @@ public class TTSUtils {
} }
/** /**
* 合并mp3文件 * 合并mp3文件,多个独立文本音频的合并和一个分段文本不同片段音频的合并都会用到这
* sox -n -r 48000 silence.wav trim 0.0 0.250
* @param filePathList 待合并mp3文件列表 * @param filePathList 待合并mp3文件列表
* @param targetFilepath 合并文件地址 * @param targetFilepath 合并文件地址
* @param xiaoai 为true代表这是多个独立文本音频的合并
* @throws IOException * @throws IOException
*/ */
public static void combineMp3File(Collection<String> filePathList, String targetFilepath, Boolean xiaoai) public static void combineMp3File(Collection<String> filePathList, String targetFilepath, Boolean xiaoai)
...@@ -625,9 +639,13 @@ public class TTSUtils { ...@@ -625,9 +639,13 @@ public class TTSUtils {
// String command = "sox "+ StringUtils.join(filePathList, " "); // String command = "sox "+ StringUtils.join(filePathList, " ");
if (filePathList.size() == 1) { if (filePathList.size() == 1) {
// 一个不合并,拷贝一份到/xiaoai 目录下,确保下次访问命中缓存
String[] arr = filePathList.toArray(new String[]{}); String[] arr = filePathList.toArray(new String[]{});
Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath), StandardCopyOption.REPLACE_EXISTING); Files.copy(Paths.get(arr[0]), Paths.get(targetFilepath), StandardCopyOption.REPLACE_EXISTING);
} else { } else {
// 对于多个独立文本音频的合并,在两个音频之间即最后要增加静默音,增强停顿感
// 下面方法就是拼接好命令执行,命令文档地址
// https://trac.ffmpeg.org/wiki/Concatenate
if (xiaoai) { if (xiaoai) {
List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList()); List<String> str = filePathList.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ") StringBuilder builder = new StringBuilder("ffmpeg ")
...@@ -640,6 +658,7 @@ public class TTSUtils { ...@@ -640,6 +658,7 @@ public class TTSUtils {
builder.append("concat=n=").append(filePathList.size()*2).append(":v=0:a=1[a] -map [a] -b:a 64k -y ").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()); CallPython.ffmpegExecute(builder.toString());
} else { } else {
// 对于分段文本不同片段语音合并要剔除合并时产生的停顿感,增强连贯性
buildSoxCutAndCombine(filePathList, targetFilepath); buildSoxCutAndCombine(filePathList, targetFilepath);
} }
} }
...@@ -676,13 +695,19 @@ public class TTSUtils { ...@@ -676,13 +695,19 @@ public class TTSUtils {
// }); // });
} }
/**
* 按顺序处理各个片段语音,切除头尾语音的后前静默片段,中间语音的前后静默
* @param filePathList 片段语音地址
* @param targetFilepath 合并后地址
*/
private static void buildSoxCutAndCombine(Collection<String> filePathList, String targetFilepath) { private static void buildSoxCutAndCombine(Collection<String> filePathList, String targetFilepath) {
long startMark = System.currentTimeMillis(); long startMark = System.currentTimeMillis();
String strMark = RandomStringUtils.random(4, true, true); String strMark = RandomStringUtils.random(4, true, true);
int i = 0, ln = filePathList.size()-1; int i = 0, ln = filePathList.size()-1;
String tempPath; String tempPath; // 每个片段语音处理后形成的新的文件地址
List<Future> resultList = new ArrayList<>(ln+1); List<Future> resultList = new ArrayList<>(ln+1); // 异步Future结果集
List<String> cutedPaths = new ArrayList<>(resultList.size()); List<String> cutedPaths = new ArrayList<>(resultList.size()); // 存储经过处理后的片段文件地址
// 关于切除静默音文档地址 https://digitalcardboard.com/blog/2009/08/25/the-sox-of-silence/
for (String sourcePath: filePathList) { for (String sourcePath: filePathList) {
StringBuilder soxCutCommand = new StringBuilder("sox "); StringBuilder soxCutCommand = new StringBuilder("sox ");
if (i == 0) { if (i == 0) {
...@@ -705,6 +730,7 @@ public class TTSUtils { ...@@ -705,6 +730,7 @@ public class TTSUtils {
} }
cutedPaths.add(tempPath); cutedPaths.add(tempPath);
} }
// 等待直到所有都完成
for (Future future: resultList) { for (Future future: resultList) {
try { try {
future.get(10, TimeUnit.SECONDS); future.get(10, TimeUnit.SECONDS);
...@@ -718,6 +744,8 @@ public class TTSUtils { ...@@ -718,6 +744,8 @@ public class TTSUtils {
} }
// long temp; // long temp;
// log.warn("sox 切除静音耗时:"+((temp=System.currentTimeMillis())-startMark)); // log.warn("sox 切除静音耗时:"+((temp=System.currentTimeMillis())-startMark));
// 调用ffmpeg命令合并,合并后的音频尾部增加一段250ms的静默音
List<String> str = cutedPaths.stream().map(s -> "-i "+s).collect(Collectors.toList()); List<String> str = cutedPaths.stream().map(s -> "-i "+s).collect(Collectors.toList());
StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")) StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " "))
.append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3") .append(" -i ").append(Initialize.getAudioDir()).append("/silence/250ms.mp3")
...@@ -728,6 +756,8 @@ public class TTSUtils { ...@@ -728,6 +756,8 @@ public class TTSUtils {
builder.append("concat=n=").append(filePathList.size()+1).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()); CallPython.ffmpegExecute(builder.toString());
// log.warn("ffmpeg 拼接耗时:"+(System.currentTimeMillis()-temp)); // log.warn("ffmpeg 拼接耗时:"+(System.currentTimeMillis()-temp));
// 片段处理后的临时文件删除
POOL.submit(() -> { POOL.submit(() -> {
for (String delPath: cutedPaths) new File(delPath).delete(); for (String delPath: cutedPaths) new File(delPath).delete();
}); });
......
...@@ -47,7 +47,7 @@ import lombok.RequiredArgsConstructor; ...@@ -47,7 +47,7 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
/** /**
* painter * 该类主要是和创作平台相关,如背景图片部署,集群时的音频部署,音频信息获取
* 20-6-11 下午7:57 * 20-6-11 下午7:57
*/ */
@CrossOrigin @CrossOrigin
...@@ -236,6 +236,19 @@ public class DeployController { ...@@ -236,6 +236,19 @@ public class DeployController {
return ServerResponse.createByErrorEnum(ResponseCode.ERROR); return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
} }
/**
* 音频部署,作品目标服务器的tts会被调用到该接口,他会不断去调源服务器的下载接口,每次指定要下载的片段是从哪个字节开始到哪结束.
* 关于该方法的理解需要先理解创作平台部署代码,创作平台图片部署代码是最新的,经过封装里面有详细注释
* @param length 源服务器文件总大小
* @param path 源服务器文件地址
* @param sourceServer 源服务器地址
* @param zipDir 压缩包目录
* @param targetDir 解压目录
* @param type 图片还是音频部署
* @param gameServer 与创作平台集群有关,指定回调的创作平台服务器地址,用于通知下载结果
* @param auth 创作平台校验码
* @return
*/
@GetMapping("/syn/download") @GetMapping("/syn/download")
public String synSysImgTargetServerDownInThread(Long length, String path, String sourceServer,String zipDir, public String synSysImgTargetServerDownInThread(Long length, String path, String sourceServer,String zipDir,
String targetDir, String type, @RequestParam(required = false) String gameServer, String targetDir, String type, @RequestParam(required = false) String gameServer,
...@@ -249,16 +262,18 @@ public class DeployController { ...@@ -249,16 +262,18 @@ public class DeployController {
return "failure"; return "failure";
} }
String botAccount = path.substring(path.lastIndexOf(File.separator)+1, path.length()-4); String botAccount = path.substring(path.lastIndexOf(File.separator)+1, path.length()-4);
String markPath = zipDir+ File.separator+botAccount+".csv"; String markPath = zipDir+ File.separator+botAccount+".csv"; //
try { try {
Path pt; Path pt;
Files.createDirectories((pt=Paths.get(markPath)).getParent()); Files.createDirectories((pt=Paths.get(markPath)).getParent());
Files.createFile(pt); Files.createFile(pt);
Path botAccountPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount); Path botAccountPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount);
if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount) && Files.exists(botAccountPt)) { if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount) && Files.exists(botAccountPt)) {
// 部署前删除所有非人工语音
Files.list(botAccountPt) Files.list(botAccountPt)
.filter(path1 -> !StringUtils.startsWith(path1.getFileName().toString(), Initialize.getUploadedDir())) .filter(path1 -> !StringUtils.startsWith(path1.getFileName().toString(), Initialize.getUploadedDir()))
.forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile())); .forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile()));
// 对于人工语音,处于谨慎考虑删除所有非mp3语音,部署后新的会替代旧的,也可全部删除
Path recordPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount+File.separator+Initialize.getUploadedDir()); Path recordPt = Paths.get(Initialize.getAudioDir()+File.separator+botAccount+File.separator+Initialize.getUploadedDir());
if (Files.exists(recordPt)) { if (Files.exists(recordPt)) {
Files.list(recordPt).forEach(npcNameDir -> { Files.list(recordPt).forEach(npcNameDir -> {
...@@ -291,9 +306,9 @@ public class DeployController { ...@@ -291,9 +306,9 @@ public class DeployController {
String auth, String botAccount, String type, String gameServer) { String auth, String botAccount, String type, String gameServer) {
log.warn("/upload/syn/download 开始:{},sourceServer:{},gameServer:{}, botAccount:{}",path, sourceServer, gameServer, botAccount); log.warn("/upload/syn/download 开始:{},sourceServer:{},gameServer:{}, botAccount:{}",path, sourceServer, gameServer, botAccount);
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
int sliceSize = 6*1024*1024; int sliceSize = 6*1024*1024; // 每片6m大小
long start = 0, end = sliceSize-1; long start = 0, end = sliceSize-1;
sourceServer += "/upload/range/download"; sourceServer += "/upload/range/download"; // 源服务器文件下载地址
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put("path", path); params.put("path", path);
params.put("pass", "mqw"+RandomStringUtils.random(3)); params.put("pass", "mqw"+RandomStringUtils.random(3));
...@@ -301,17 +316,20 @@ public class DeployController { ...@@ -301,17 +316,20 @@ public class DeployController {
Map<String, String> headers = new HashMap<>(); Map<String, String> headers = new HashMap<>();
headers.put("Authorization", auth); headers.put("Authorization", auth);
String prefix = RandomStringUtils.randomAlphabetic(5); String prefix = RandomStringUtils.randomAlphabetic(5);
String tempSliceName = zipDir+ File.separator+ prefix+"_"; String tempSliceName = zipDir+ File.separator+ prefix+"_"; // 同一作品每个片段名共同前缀
try { try {
Files.createDirectories(Paths.get(zipDir)); Files.createDirectories(Paths.get(zipDir));
int i = 1; int i = 1; // 统计一共有多少片段
// 存储片段地址及下载结果
ConcurrentHashMap<String, String> recordAlreadyFineSlice = new ConcurrentHashMap<>(); ConcurrentHashMap<String, String> recordAlreadyFineSlice = new ConcurrentHashMap<>();
Semaphore semaphore = new Semaphore(6); Semaphore semaphore = new Semaphore(6); // 下载请求是异步的,这里最多允许6个最打并发请求数
while (start < length) { while (start < length) {
// 指定下载的开始和结束字节下标
if (end >= length-1) headers.put("Range", "bytes="+start+"-"); if (end >= length-1) headers.put("Range", "bytes="+start+"-");
else headers.put("Range", "bytes="+start+"-"+end); else headers.put("Range", "bytes="+start+"-"+end);
try { try {
semaphore.acquire(); semaphore.acquire();
// 发起异步下载请求
ApachHttpUtils.asyncFileDataDownloadGet(sourceServer, params, headers, ApachHttpUtils.asyncFileDataDownloadGet(sourceServer, params, headers,
tempSliceName+i++, recordAlreadyFineSlice,semaphore); tempSliceName+i++, recordAlreadyFineSlice,semaphore);
} catch (InterruptedException e) { } catch (InterruptedException e) {
...@@ -320,9 +338,11 @@ public class DeployController { ...@@ -320,9 +338,11 @@ public class DeployController {
start = end+1; start = end+1;
end += sliceSize; end += sliceSize;
} }
// 读取所有片段合并成完整压缩包
FileChannel toChannel = new RandomAccessFile(tempSliceName+".zip", "rw").getChannel(); FileChannel toChannel = new RandomAccessFile(tempSliceName+".zip", "rw").getChannel();
String slice; String slice;
String res; String res;
// 确保每个片段都下载完成,等待未完成的片段,通过recordAlreadyFineSlice来获悉该片段的下载结果
for (int j = 1; j < i; j++) { for (int j = 1; j < i; j++) {
slice = tempSliceName+j; slice = tempSliceName+j;
int num = 0; int num = 0;
...@@ -335,6 +355,7 @@ public class DeployController { ...@@ -335,6 +355,7 @@ public class DeployController {
} }
++num; ++num;
} }
// 下载接口未响应,返回失败
if (res == null) { if (res == null) {
log.error("180s仍未获取到响应信息"); log.error("180s仍未获取到响应信息");
deleteSlice(zipDir, prefix, botAccount); deleteSlice(zipDir, prefix, botAccount);
...@@ -343,7 +364,9 @@ public class DeployController { ...@@ -343,7 +364,9 @@ public class DeployController {
ApachHttpUtils.asyncDelete(sourceServer, params, headers); ApachHttpUtils.asyncDelete(sourceServer, params, headers);
return; return;
} }
// 针对某些片段下载失败重试
if ("failure".equals(res)) { if ("failure".equals(res)) {
log.warn("片段{}下载失败,开始重试", slice);
int count = 0; int count = 0;
boolean success; boolean success;
do { do {
...@@ -363,6 +386,7 @@ public class DeployController { ...@@ -363,6 +386,7 @@ public class DeployController {
return; return;
} }
} }
// 读取片段数据写入到总压缩包文件中
FileChannel fromChannel = new RandomAccessFile(slice, "r").getChannel(); FileChannel fromChannel = new RandomAccessFile(slice, "r").getChannel();
fromChannel.transferTo(0, fromChannel.size(), toChannel); fromChannel.transferTo(0, fromChannel.size(), toChannel);
fromChannel.close(); fromChannel.close();
...@@ -371,8 +395,8 @@ public class DeployController { ...@@ -371,8 +395,8 @@ public class DeployController {
toChannel.close(); toChannel.close();
if ("audio".equals(targetDir)) FileUtil.deleteFile(new File(targetDir)); if ("audio".equals(targetDir)) FileUtil.deleteFile(new File(targetDir));
Files.createDirectories(Paths.get(targetDir)); Files.createDirectories(Paths.get(targetDir));
FileUtil.decompress(tempSliceName+".zip", targetDir); FileUtil.decompress(tempSliceName+".zip", targetDir); // 解压
deleteSlice(zipDir, prefix, botAccount); deleteSlice(zipDir, prefix, botAccount); // 删除下载片段
params.put("result", "success"); params.put("result", "success");
params.put("gameServer", gameServer); params.put("gameServer", gameServer);
// if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount)) { // if (!"image_deploy".equals(type) && StringUtils.isNotBlank(botAccount)) {
...@@ -381,7 +405,7 @@ public class DeployController { ...@@ -381,7 +405,7 @@ public class DeployController {
//// .forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile())); //// .forEach(path1 -> FileUtil.deleteFile(path1.toAbsolutePath().toFile()));
// FileUtil.deleteFile(new File(Initialize.getAudioDir()+File.separator+botAccount+File.separator+"xiaoai")); // FileUtil.deleteFile(new File(Initialize.getAudioDir()+File.separator+botAccount+File.separator+"xiaoai"));
// } // }
ApachHttpUtils.asyncDelete(sourceServer, params, headers); ApachHttpUtils.asyncDelete(sourceServer, params, headers); // 通知源服务器下载结果
} catch (IOException e) { } catch (IOException e) {
deleteSlice(zipDir, prefix, botAccount); deleteSlice(zipDir, prefix, botAccount);
params.put("result", "failure"); params.put("result", "failure");
...@@ -409,6 +433,11 @@ public class DeployController { ...@@ -409,6 +433,11 @@ public class DeployController {
} }
} }
// ====================
// 下面的是与gameditor集群版音频部署相关的一些接口
// 关于他们的文档在gameditor项目里,通过图片部署接口去查看如何使用,里面有详细的文档说明
// =======================
/** /**
* *
* @param path 被压缩文件路径 * @param path 被压缩文件路径
...@@ -587,6 +616,11 @@ public class DeployController { ...@@ -587,6 +616,11 @@ public class DeployController {
} }
} }
// ======================= 集群服务器部署相关代码到此结束 =======
// 下面的是与gameditor相关的一些接口,有些已经废除,暂不清楚
@PostMapping("/audio/move/background") @PostMapping("/audio/move/background")
public String moveBotBackgroundAudio(@RequestBody MoveBotAudio moveBotAudio) { public String moveBotBackgroundAudio(@RequestBody MoveBotAudio moveBotAudio) {
try { try {
......
...@@ -543,7 +543,7 @@ public class TTSController { ...@@ -543,7 +543,7 @@ public class TTSController {
} }
/** /**
* 合成后的回调 * 创作平台离线语音功能合成后的回调
* @param file 文件 * @param file 文件
* @param response 响应信息 * @param response 响应信息
*/ */
......
package ai.qiwu.com.tts_service.controller;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* painter
* 20-10-30 下午9:30
*/
@Getter
@Setter
@ToString
public class TempPersonInfo {
private String name;
private String sex;
private List<String> mood;
private Boolean third_party;
}
package ai.qiwu.com.tts_service.controller;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.Map;
/**
* painter
* 20-10-30 下午9:29
*/
@Getter
@Setter
@ToString
public class TempSpeakersApi {
private Map<String, TempPersonInfo> online;
private Map<String, TempPersonInfo> offline;
}
...@@ -1959,7 +1959,7 @@ public class TTService { ...@@ -1959,7 +1959,7 @@ public class TTService {
// } // }
/** /**
* * 音频压缩包中不能含有目录
* @param data * @param data
* @param response * @param response
* @param head * @param head
...@@ -2010,6 +2010,7 @@ public class TTService { ...@@ -2010,6 +2010,7 @@ public class TTService {
// 判断该文件的编码 // 判断该文件的编码
String encoding = TTSUtils.charset(csvFile); String encoding = TTSUtils.charset(csvFile);
// 修改音频的采样率和比特率
int sampleRate = data.getSampleRate() == null ? 44100 : data.getSampleRate(); int sampleRate = data.getSampleRate() == null ? 44100 : data.getSampleRate();
String bitRate = StringUtils.isBlank(data.getBitRate()) ? "64k" : data.getBitRate(); String bitRate = StringUtils.isBlank(data.getBitRate()) ? "64k" : data.getBitRate();
switch (bitRate) { switch (bitRate) {
...@@ -2032,43 +2033,53 @@ public class TTService { ...@@ -2032,43 +2033,53 @@ public class TTService {
} }
// 意料之外的错误发生,无法判断程序进度,记录该种情况最后根据情况返回相应的信息 // 意料之外的错误发生,无法判断程序进度,记录该种情况最后根据情况返回相应的信息
final List<String> needDeleteB64File = new ArrayList<>();
Set<String> successUpLoadFileIds = new HashSet<>(); final List<String> needDeleteB64File = new ArrayList<>(); // 存储需要删除的旧的音频的b64文件地址
HashSet<String> textSet = new HashSet<>(); Set<String> successUpLoadFileIds = new HashSet<>(); // 部署成功的文本的id,用于回调通知gameditor改变文本数据库音频状态
List<String> failList = new ArrayList<>(); HashSet<String> textSet = new HashSet<>(); // 用于去重,同一文本只部署一次
int repeate = 0; List<String> failList = new ArrayList<>(); // 部署失败的文本id列表
int noeTextSameId = 0; int repeate = 0; // 重复的文本个数
int empty = 0; int noeTextSameId = 0; // 记录总共有多少文本id,不包含重复
int all = 0; int empty = 0; // 没有指定音频名称的记录数
int all = 0; // 出去第一行外总记录数
boolean firstLine = true; boolean firstLine = true;
// 遍历读取每一行
try (CSVParser parser = CSVFormat.EXCEL.withHeader("内部代号", "句子", "是否已上传音频文件", "音频文件名").parse(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), Charset.forName(encoding))))){ try (CSVParser parser = CSVFormat.EXCEL.withHeader("内部代号", "句子", "是否已上传音频文件", "音频文件名").parse(new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), Charset.forName(encoding))))){
for (CSVRecord record : parser) { for (CSVRecord record : parser) {
// 过滤第一行,头
if (firstLine) { if (firstLine) {
firstLine = false; firstLine = false;
continue; continue;
} }
all++; all++;
String audioFileName; String audioFileName;
// 没有指定音频名称
if (StringUtils.isBlank((audioFileName = record.get(3)))) { if (StringUtils.isBlank((audioFileName = record.get(3)))) {
empty++; empty++;
continue; continue;
} }
// 重复,之前的已成功,直接记录该文本id
if (!textSet.add(record.get(1))) { if (!textSet.add(record.get(1))) {
boolean bn = successUpLoadFileIds.add(record.get(0)); boolean bn = successUpLoadFileIds.add(record.get(0));
if (!bn) repeate++; if (!bn) repeate++;
continue; continue;
} }
// 没有mp3后缀名的增加.mp3后缀
boolean hasSuffix = StringUtils.endsWith(audioFileName,".mp3") || StringUtils.endsWith(audioFileName,".MP3"); boolean hasSuffix = StringUtils.endsWith(audioFileName,".mp3") || StringUtils.endsWith(audioFileName,".MP3");
if (!hasSuffix) audioFileName = audioFileName+".mp3"; if (!hasSuffix) audioFileName = audioFileName+".mp3";
// 音频地址
String fileInPackage = zipFolder + File.separator + audioFileName; String fileInPackage = zipFolder + File.separator + audioFileName;
String md5Name = TTSUtils.buildMP3Filename(record.get(1)); //构造mp3文件名 String md5Name = TTSUtils.buildMP3Filename(record.get(1)); //构造mp3文件名
// 音频部署地址
final String usFilename = new StringBuilder(folder).append(File.separator).append(md5Name).toString(); final String usFilename = new StringBuilder(folder).append(File.separator).append(md5Name).toString();
// 如果音频不存在且用户未指定后缀,则讲后缀改为.MP3,查看文件是否存在
boolean doesFileExit = TTSUtils.doesFileExist(fileInPackage); boolean doesFileExit = TTSUtils.doesFileExist(fileInPackage);
if (!doesFileExit && !hasSuffix) { if (!doesFileExit && !hasSuffix) {
fileInPackage = new StringBuilder(zipFolder).append(File.separator) fileInPackage = new StringBuilder(zipFolder).append(File.separator)
.append(record.get(3)).append(".MP3").toString(); .append(record.get(3)).append(".MP3").toString();
doesFileExit = TTSUtils.doesFileExist(fileInPackage); doesFileExit = TTSUtils.doesFileExist(fileInPackage);
} }
//
if (doesFileExit) { if (doesFileExit) {
File usFile = new File(usFilename); File usFile = new File(usFilename);
boolean result=true; boolean result=true;
...@@ -2079,27 +2090,34 @@ public class TTService { ...@@ -2079,27 +2090,34 @@ public class TTService {
// 删除成功后删除其b64文件,且将压缩包中的文件移到安置目录下,即 // 删除成功后删除其b64文件,且将压缩包中的文件移到安置目录下,即
// /root/TTS-service/mqwZip/audioFilename -> audio_dir/botname/record/npcname/xxx.mp3 // /root/TTS-service/mqwZip/audioFilename -> audio_dir/botname/record/npcname/xxx.mp3
if (result) { if (result) {
needDeleteB64File.add(usFilename + ".b64"); needDeleteB64File.add(usFilename + ".b64"); // 记录要删除的b64文件最后一起异步删除
try { try {
// 拷贝
Files.copy(new File(fileInPackage).toPath(), usFile.toPath()); Files.copy(new File(fileInPackage).toPath(), usFile.toPath());
// 改变采样率和比特率并在结尾增加250ms的静默尾音
if (TTSUtils.changeAudioConfigAddSilence(sampleRate, bitRate, usFilename)) { if (TTSUtils.changeAudioConfigAddSilence(sampleRate, bitRate, usFilename)) {
// 存储成功的文本id
boolean bn = successUpLoadFileIds.add(record.get(0)); boolean bn = successUpLoadFileIds.add(record.get(0));
if (!bn) noeTextSameId++; if (!bn) noeTextSameId++;
} else { } else {
// 失败,删除textSet中的记录,记录该失败的文本id
log.warn("打包上传音频转换采样率/比特率数据失败,"+usFilename); log.warn("打包上传音频转换采样率/比特率数据失败,"+usFilename);
failList.add(record.get(0)); failList.add(record.get(0));
textSet.remove(record.get(1)); textSet.remove(record.get(1));
} }
} catch (Exception e) { } catch (Exception e) {
// 失败,删除textSet中的记录,记录该失败的文本id
failList.add(record.get(0)); failList.add(record.get(0));
textSet.remove(record.get(1)); textSet.remove(record.get(1));
} }
}else { }else {
// 失败,删除textSet中的记录,记录该失败的文本id
failList.add(record.get(0)); failList.add(record.get(0));
textSet.remove(record.get(1)); textSet.remove(record.get(1));
log.error("删除之前的就音频失败:{}",fileInPackage); log.error("删除之前的就音频失败:{}",fileInPackage);
} }
} else { } else {
// 文件不存在,删除textSet中的记录,记录该失败的文本id
textSet.remove(record.get(1)); textSet.remove(record.get(1));
failList.add(record.get(0)); failList.add(record.get(0));
} }
...@@ -2188,7 +2206,10 @@ public class TTService { ...@@ -2188,7 +2206,10 @@ public class TTService {
// log.error("打包上传回调出现错误:{}",ExceptionUtils.getStackTrace(e)); // log.error("打包上传回调出现错误:{}",ExceptionUtils.getStackTrace(e));
// } // }
// }); // });
// 处理的总共个数 = 成功的文本个数(不包含重复)+重复文本个数+重复文本id个数+未指定音频名个数
int sum = successUpLoadFileIds.size()+repeate+noeTextSameId+empty; int sum = successUpLoadFileIds.size()+repeate+noeTextSameId+empty;
// 回调gameditor告知成功的文本id
try { try {
successUpLoadFileIds = successUpLoadFileIds.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet()); successUpLoadFileIds = successUpLoadFileIds.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
log.info("打包上传成功id个数:{}",successUpLoadFileIds.size()); log.info("打包上传成功id个数:{}",successUpLoadFileIds.size());
...@@ -2211,6 +2232,7 @@ public class TTService { ...@@ -2211,6 +2232,7 @@ public class TTService {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(500, "打包上传回调出现错误,请确认下csv文件第四列是否全为空"), 500); TTServiceUtil.buildUploadResponse(response, new TTSResponse(500, "打包上传回调出现错误,请确认下csv文件第四列是否全为空"), 500);
return zipFolder; return zipFolder;
} }
// 删除压缩包,b64文件
POOL.submit(() -> { POOL.submit(() -> {
FileUtil.deleteFile(new File(StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), "xiaoai"},File.separator))); FileUtil.deleteFile(new File(StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(), "xiaoai"},File.separator)));
TTSUtils.deleteFile(new File(zipFolder)); TTSUtils.deleteFile(new File(zipFolder));
...@@ -2221,6 +2243,8 @@ public class TTService { ...@@ -2221,6 +2243,8 @@ public class TTService {
// List<Path> pts = FileUtil.getThePathAllMp3File(recordPath); // List<Path> pts = FileUtil.getThePathAllMp3File(recordPath);
}); });
//log.info("msg:{}",msg); //log.info("msg:{}",msg);
// 没有失败的文本存在,sum 和 all的值,分情况返回信息
if (failList.size() == 0) { if (failList.size() == 0) {
if (sum == all) { if (sum == all) {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, "全部成功"), 200); TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, "全部成功"), 200);
...@@ -2230,6 +2254,9 @@ public class TTService { ...@@ -2230,6 +2254,9 @@ public class TTService {
TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, info), 200); TTServiceUtil.buildUploadResponse(response, new TTSResponse(200, info), 200);
} }
} else { } else {
// 有失败的则根据sum 与 all 值对比,分情况返回信息
// 剔除 内部代号 影响
if ("内部代号".equals(failList.get(0))) failList.remove(0); if ("内部代号".equals(failList.get(0))) failList.remove(0);
if (failList.size() == 0) { if (failList.size() == 0) {
if (sum + 1 == all) { if (sum + 1 == all) {
......
...@@ -1303,15 +1303,15 @@ public class TTServiceEdition2 { ...@@ -1303,15 +1303,15 @@ public class TTServiceEdition2 {
} }
/** /**
* * 请求b64文件数据,该种请求是同步的需要等待文件下载完成
* @param response * @param response HttpServletResponse
* @param file_ls * @param file_ls 文件地址
* @param botName * @param botName 作品id
* @param _type * @param _type 请求类型不通返回不同,url指访问地址,b64指b64文件数据,filename指文件的路径
*/ */
private void dealHasB64FileRequest(HttpServletResponse response, private void dealHasB64FileRequest(HttpServletResponse response,
List<String> file_ls, String botName, String _type) { List<String> file_ls, String botName, String _type) {
// 若请求字段_type为filename,则返回.b64文件的路径列表,负责返回所有.b64文件的内容数据 // 若请求字段_type为filename,则返回.b64文件的路径列表,否则返回所有.b64文件的内容数据
TtsLsResponse ttsLsResponse = new TtsLsResponse(); TtsLsResponse ttsLsResponse = new TtsLsResponse();
try { try {
switch (TtsLsType.valueOf(_type)) { switch (TtsLsType.valueOf(_type)) {
...@@ -1336,6 +1336,14 @@ public class TTServiceEdition2 { ...@@ -1336,6 +1336,14 @@ public class TTServiceEdition2 {
TTServiceUtil.buildNewTtsLsResponse(response, ttsLsResponse, HttpServletResponse.SC_OK); TTServiceUtil.buildNewTtsLsResponse(response, ttsLsResponse, HttpServletResponse.SC_OK);
} }
/**
* 请求mp3文件访问地址,该种请求是异步的,无需等待文件下载完成
* @param response HttpServletResponse
* @param file_ls 文件地址
* @param botName 作品id
* @param _type 请求类型不通返回不同,url指访问地址,b64指b64文件数据,filename指文件的路径
* @param xiaoai 是否合并
*/
private void dealMp3UrlRequest(HttpServletResponse response, List<String> file_ls, private void dealMp3UrlRequest(HttpServletResponse response, List<String> file_ls,
String botName, String _type, boolean xiaoai) { String botName, String _type, boolean xiaoai) {
// 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3, // 小爱平台的请求,我们会讲所有mp3文件合在一起,文件路径为(audio_dir)/botname/xiaoai/xxx.mp3,
...@@ -1345,7 +1353,7 @@ public class TTServiceEdition2 { ...@@ -1345,7 +1353,7 @@ public class TTServiceEdition2 {
String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name.substring(23); String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name.substring(23);
// String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name; // String audio = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="+tmp_audio_name;
if (!Files.exists(Paths.get(tmp_audio_name))) { if (!Files.exists(Paths.get(tmp_audio_name))) {
audio += "&exist=1"; audio += "&exist=1"; // 优化字段,告知之后的访问音频接口文件已存在
} }
TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(audio,HttpServletResponse.SC_OK), null, HttpServletResponse.SC_OK); TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(audio,HttpServletResponse.SC_OK), null, HttpServletResponse.SC_OK);
} else { } else {
...@@ -1377,6 +1385,11 @@ public class TTServiceEdition2 { ...@@ -1377,6 +1385,11 @@ public class TTServiceEdition2 {
} }
} }
/**
* 将b64文件数据写入返回对象
* @param response TtsLsResponse
* @param file_ls 文件地址
*/
private void buildB64Response(TtsLsResponse response, List<String> file_ls) { private void buildB64Response(TtsLsResponse response, List<String> file_ls) {
for (String filename : file_ls) { for (String filename : file_ls) {
TtsLsAudio audio = new TtsLsAudio(); TtsLsAudio audio = new TtsLsAudio();
...@@ -1396,6 +1409,12 @@ public class TTServiceEdition2 { ...@@ -1396,6 +1409,12 @@ public class TTServiceEdition2 {
} }
} }
/**
* 将b64文件数据和访问url写入返回对象
* @param ttsLsResponse TtsLsResponse
* @param file_ls 文件地址
* @param botName 作品id
*/
private void buildB64UrlResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) { private void buildB64UrlResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) {
String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename=";
for (String path: file_ls) { for (String path: file_ls) {
...@@ -1412,12 +1431,17 @@ public class TTServiceEdition2 { ...@@ -1412,12 +1431,17 @@ public class TTServiceEdition2 {
log.error("读取文件{}.b64内容出错:{}", path, e.toString()); log.error("读取文件{}.b64内容出错:{}", path, e.toString());
audio.setB64(""); audio.setB64("");
} }
audio.setUrl(pre+path.substring(23)); audio.setUrl(pre+path.substring(23)); // 剔除绝对路径前缀 /root/TTS-service/audio
// audio.setUrl(pre+path); // audio.setUrl(pre+path);
ttsLsResponse.getAudio().add(audio); ttsLsResponse.getAudio().add(audio);
} }
} }
/**
* 将b64文件数据和文件名写入返回对象
* @param ttsLsResponse TtsLsResponse
* @param file_ls 文件地址
*/
private void buildB64FileNameResponse(TtsLsResponse ttsLsResponse, List<String> file_ls) { private void buildB64FileNameResponse(TtsLsResponse ttsLsResponse, List<String> file_ls) {
for (String path: file_ls) { for (String path: file_ls) {
TtsLsAudio audio = new TtsLsAudio(); TtsLsAudio audio = new TtsLsAudio();
...@@ -1428,7 +1452,7 @@ public class TTServiceEdition2 { ...@@ -1428,7 +1452,7 @@ public class TTServiceEdition2 {
continue; continue;
} }
path = path+".b64"; path = path+".b64";
audio.setFilename(path.substring(23)); audio.setFilename(path.substring(23));// 剔除绝对路径前缀 /root/TTS-service/audio
// audio.setFilename(path); // audio.setFilename(path);
try { try {
audio.setB64(TTSUtils.readAllFile(path)); audio.setB64(TTSUtils.readAllFile(path));
...@@ -1440,6 +1464,12 @@ public class TTServiceEdition2 { ...@@ -1440,6 +1464,12 @@ public class TTServiceEdition2 {
} }
} }
/**
* 将访问url写入返回对象
* @param ttsLsResponse TtsLsResponse
* @param file_ls 文件地址
* @param botName 作品id
*/
private void buildUrlResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) { private void buildUrlResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) {
String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename=";
for (String path: file_ls) { for (String path: file_ls) {
...@@ -1449,18 +1479,24 @@ public class TTServiceEdition2 { ...@@ -1449,18 +1479,24 @@ public class TTServiceEdition2 {
ttsLsResponse.getAudio().add(audio); ttsLsResponse.getAudio().add(audio);
continue; continue;
} }
String relative = path.substring(23); String relative = path.substring(23); // 剔除绝对路径前缀 /root/TTS-service/audio
// String relative = path; // String relative = path;
if (Files.exists(Paths.get(path))) { if (Files.exists(Paths.get(path))) {
audio.setUrl(pre+relative); audio.setUrl(pre+relative);
// audio.setUrl(pre+path); // audio.setUrl(pre+path);
} else { } else {
audio.setUrl(pre+relative+"&exist=1"); audio.setUrl(pre+relative+"&exist=1"); // 优化,告知访问接口文件已存在
} }
ttsLsResponse.getAudio().add(audio); ttsLsResponse.getAudio().add(audio);
} }
} }
/**
* 将访问url和b64文件地址名写入返回对象
* @param ttsLsResponse TtsLsResponse
* @param file_ls 文件地址
* @param botName 作品id
*/
private void buildUrlFileResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) { private void buildUrlFileResponse(TtsLsResponse ttsLsResponse, List<String> file_ls, String botName) {
String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename="; String pre = Initialize.getServerUrlCdn()+"/api/audio/cache/"+botName+"/?filename=";
for (String path: file_ls) { for (String path: file_ls) {
...@@ -1472,26 +1508,33 @@ public class TTServiceEdition2 { ...@@ -1472,26 +1508,33 @@ public class TTServiceEdition2 {
continue; continue;
} }
String relativePath; String relativePath;
audio.setFilename((relativePath=path.substring(23))+".b64"); audio.setFilename((relativePath=path.substring(23))+".b64"); // 剔除绝对路径前缀 /root/TTS-service/audio
// audio.setFilename((relativePath=path)+".b64"); // audio.setFilename((relativePath=path)+".b64");
if (Files.exists(Paths.get(path))) { if (Files.exists(Paths.get(path))) {
audio.setUrl(pre+relativePath); audio.setUrl(pre+relativePath);
} else { } else {
audio.setUrl(pre+relativePath+"&exist=1"); audio.setUrl(pre+relativePath+"&exist=1"); // 优化,告知访问接口文件已存在
} }
ttsLsResponse.getAudio().add(audio); ttsLsResponse.getAudio().add(audio);
} }
} }
/**
* 将文件地址名写入返回对象
* @param ttsLsResponse TtsLsResponse
* @param file_ls 文件地址
*/
private void buildFilenameResponse(TtsLsResponse ttsLsResponse, List<String> file_ls) { private void buildFilenameResponse(TtsLsResponse ttsLsResponse, List<String> file_ls) {
for (String name: file_ls) { for (String name: file_ls) {
TtsLsAudio audio = new TtsLsAudio(); TtsLsAudio audio = new TtsLsAudio();
audio.setFilename(name.substring(23)); audio.setFilename(name.substring(23)); // 剔除绝对路径前缀 /root/TTS-service/audio
// audio.setFilename(name); // audio.setFilename(name);
ttsLsResponse.getAudio().add(audio); ttsLsResponse.getAudio().add(audio);
} }
} }
// 下面的这两个方法都与音箱有关,是针对音箱获取文本音频访问链接的专门优化,
// 大致流程都与tts_ls方法相同
public String apiAudio(ApiAudioData apiAudioData) { public String apiAudio(ApiAudioData apiAudioData) {
List<Dialog> dialogs = apiAudioData.getDialogs(); List<Dialog> dialogs = apiAudioData.getDialogs();
// botname不能为空 // botname不能为空
......
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