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