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 9871ee6..05c7d55 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 @@ -65,20 +65,26 @@ public class TTSController { // private final TtsLsService ttsLsService; + /** + * 主要实现类TTService的第二版 + */ private final TTServiceEdition2 ttServiceEdition2; + /** + * 用于主动更新猎户语音的Token使用 + */ private final LieHuSchedule lieHuSchedule; - @Autowired - public SpeakerInfoRepository speakerInfoRepository; +// @Autowired +// public SpeakerInfoRepository speakerInfoRepository; // private final CdnService cdnService; // @Autowired // private StringRedisTemplate stringRedisTemplate; - private static volatile Map offline; - private static volatile Map online; +// private static volatile Map offline; +// private static volatile Map online; @Autowired public TTSController(TTService ttService, TTServiceEdition2 ttServiceEdition2, LieHuSchedule lieHuSchedule) { @@ -89,56 +95,56 @@ public class TTSController { } // @GetMapping("/api/add/slice") - public String addSlice(String botName) { - try { - Files.list(Paths.get(Initialize.getAudioDir()+File.separator+botName+"/record/")).forEach(path -> { - try { - Files.list(path).filter(path1 -> StringUtils.endsWith(path1.getFileName().toString(), ".mp3")) - .forEach(path1 -> { - if (!TTSUtils.addAudioSlice(path1.toAbsolutePath().toString())) { - log.warn("addSlice fail:path:"+path.toAbsolutePath().toString()); - } - }); - } catch (Exception e) { - log.error("addSlice fail:{}, dir path:{}", e, path.toString()); - } - }); - return "success"; - } catch (Exception e) { - log.error("addSlice fail:{}", e); - } - return "fail"; - } +// public String addSlice(String botName) { +// try { +// Files.list(Paths.get(Initialize.getAudioDir()+File.separator+botName+"/record/")).forEach(path -> { +// try { +// Files.list(path).filter(path1 -> StringUtils.endsWith(path1.getFileName().toString(), ".mp3")) +// .forEach(path1 -> { +// if (!TTSUtils.addAudioSlice(path1.toAbsolutePath().toString())) { +// log.warn("addSlice fail:path:"+path.toAbsolutePath().toString()); +// } +// }); +// } catch (Exception e) { +// log.error("addSlice fail:{}, dir path:{}", e, path.toString()); +// } +// }); +// return "success"; +// } catch (Exception e) { +// log.error("addSlice fail:{}", e); +// } +// return "fail"; +// } - @GetMapping("/change/bot/all/audio") - public void changeOneBotAllAudio(String botName) throws IOException { - String botRecord = String.join(File.separator, Initialize.getAudioDir(), botName, Initialize.getUploadedDir()); - AtomicInteger recordMp3Num = new AtomicInteger(0); - AtomicLong recordMp3FileSize = new AtomicLong(0); - AtomicLong afterChangeSize = new AtomicLong(0); - Files.list(Paths.get(botRecord)).forEach(path -> { - try { - Files.list(path).forEach(path1 -> { - try { - - if (StringUtils.endsWith(path1.getFileName().toString(), ".mp3")) { - recordMp3Num.getAndIncrement(); - recordMp3FileSize.addAndGet(Files.size(path1)); - TTSUtils.changeAudioConfigAddSilence(44100, "64k", path1.toAbsolutePath().toString()); - afterChangeSize.addAndGet(Files.size(path1)); - } else { - Files.deleteIfExists(path1); - } - } catch (Exception e) { - log.error("changeOneBotAllAudio :{}, path1:{}",e,path1.toString()); - } - }); - } catch (Exception e) { - log.error("changeOneBotAllAudio :{}, path:{}",e,path.toString()); - } - }); - log.info("num:{}, beforeSize:{}, afterSize:{}", recordMp3Num.get(), recordMp3FileSize, afterChangeSize); - } +// @GetMapping("/change/bot/all/audio") +// public void changeOneBotAllAudio(String botName) throws IOException { +// String botRecord = String.join(File.separator, Initialize.getAudioDir(), botName, Initialize.getUploadedDir()); +// AtomicInteger recordMp3Num = new AtomicInteger(0); +// AtomicLong recordMp3FileSize = new AtomicLong(0); +// AtomicLong afterChangeSize = new AtomicLong(0); +// Files.list(Paths.get(botRecord)).forEach(path -> { +// try { +// Files.list(path).forEach(path1 -> { +// try { +// +// if (StringUtils.endsWith(path1.getFileName().toString(), ".mp3")) { +// recordMp3Num.getAndIncrement(); +// recordMp3FileSize.addAndGet(Files.size(path1)); +// TTSUtils.changeAudioConfigAddSilence(44100, "64k", path1.toAbsolutePath().toString()); +// afterChangeSize.addAndGet(Files.size(path1)); +// } else { +// Files.deleteIfExists(path1); +// } +// } catch (Exception e) { +// log.error("changeOneBotAllAudio :{}, path1:{}",e,path1.toString()); +// } +// }); +// } catch (Exception e) { +// log.error("changeOneBotAllAudio :{}, path:{}",e,path.toString()); +// } +// }); +// log.info("num:{}, beforeSize:{}, afterSize:{}", recordMp3Num.get(), recordMp3FileSize, afterChangeSize); +// } /** * 删除bot缓存,会将对应目录下的非人工音频文件全部删除 @@ -203,7 +209,8 @@ public class TTSController { @RequestParam(required = false) String _type, @RequestParam(required = false) String volume, @RequestParam(required = false) String pitch, @RequestParam(required = false) String speed, @RequestParam(required = false) Boolean get_online, @RequestParam(required = false) String npcName,HttpServletResponse servletResponse) { - TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed,get_online,npcName); + TTSRequest ttsRequest = new TTSRequest(person,text,_type,tone,botname,get_online,npcName,volume,speed,pitch); +// TTSRequest ttsRequest = new TTSRequest(person, text, _type, pitch, tone, botname, volume, speed,get_online,npcName); // ttService.tts(ttsRequest, "GET", servletResponse); ttServiceEdition2.tts(ttsRequest, "GET", servletResponse); } @@ -309,16 +316,35 @@ public class TTSController { ttService.uploadOneSen(data, response, request.getHeader("Authorization"), request.getHeader("groupId"), request.getHeader("botAccount")); } + /** + * 改变某音频的采样率和比特率 + * @param data 数据 + * + * @return ServerResponse + */ @PutMapping("/api/upload/record/one_sen") public ServerResponse updateAudioConfig(@RequestBody UploadOneSenData data) { return ttService.changeOneSenAudioConfig(data); } + /** + * 获取音频文件比特率,时长,采样率等配置信息 + * @param botName bot id + * @param npcName 角色名 + * @param text 文本 + * @param onlyCheckExist 不为空时说明只是用来探测文件是否存在使用,用于gameditor调用 + * @return + */ @GetMapping("/api/upload/record/one_sen") public ServerResponse getAudioConfig(String botName, String npcName, String text, @RequestParam(required = false) String onlyCheckExist) { return ttService.getOneSenAudioConfig(botName, npcName, text, onlyCheckExist); } + /** + * 改变某个音频或某角色全部音频音量大小 + * @param volume + * @return + */ @PutMapping("/api/record/volume") public ServerResponse changeRecordVolume(@RequestBody ChangeRecordVolume volume) { ServerResponse response = ttService.changeRecoedVolume(volume); @@ -329,82 +355,82 @@ public class TTSController { } // @GetMapping("/api/del/all/up") - public ServerResponse delAllUpAudio() throws IOException { - Set onlinedNames = Initialize.getPersonInfoOnline().keySet().stream().filter(s -> s.length() == 3).collect(Collectors.toSet()); - Files.list(Paths.get("/root/TTS-service/audio")).forEach(pt -> { - try { - Files.list(pt).filter(path -> onlinedNames.contains(path.getFileName().toString())).forEach(path -> FileUtil.deleteFile(path.toFile())); - } catch (IOException e) { - log.error(ExceptionUtils.getStackTrace(e)); - } - }); - return ServerResponse.createBySuccess(); - } +// public ServerResponse delAllUpAudio() throws IOException { +// Set onlinedNames = Initialize.getPersonInfoOnline().keySet().stream().filter(s -> s.length() == 3).collect(Collectors.toSet()); +// Files.list(Paths.get("/root/TTS-service/audio")).forEach(pt -> { +// try { +// Files.list(pt).filter(path -> onlinedNames.contains(path.getFileName().toString())).forEach(path -> FileUtil.deleteFile(path.toFile())); +// } catch (IOException e) { +// log.error(ExceptionUtils.getStackTrace(e)); +// } +// }); +// return ServerResponse.createBySuccess(); +// } // @GetMapping("/api/del/fragment") - public ServerResponse delAllFragment() throws IOException { - List botAccountPathList = Files.list(Paths.get("/root/TTS-service/audio")) - .filter(path -> !StringUtils.startsWithAny(path.getFileName().toString(), "miao", "mqw", "test", "tmp")) - .collect(Collectors.toList()); - for (Path bpt: botAccountPathList) { - List personPathList = Files.list(bpt).filter(path -> !StringUtils.equalsAny(path.getFileName().toString(), "xiaoai", "record")) - .collect(Collectors.toList()); - for (Path ppt: personPathList) { - List moodPathList =Files.list(ppt).filter(path -> { - boolean result = Files.isDirectory(path); - if (!result) { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - log.error("error:"+e); - } - } - return result; - }).collect(Collectors.toList()); - for (Path mpt: moodPathList) { - List mp3WavPathList = Files.list(mpt).filter(path -> !Files.isDirectory(path) && - StringUtils.endsWithAny(path.getFileName().toString(), ".wav", ".mp3")) - .collect(Collectors.toList()); - Map map = new HashMap<>(); - String filename; - for (Path mwpt: mp3WavPathList) { - filename = mwpt.getFileName().toString(); - filename = filename.substring(0, filename.indexOf(".")); - if (map.remove(filename) == null) { - map.put(filename, mwpt); - } - } - List fragmentList = map.values().stream().map(path -> path.toAbsolutePath().toString()).collect(Collectors.toList()); - if (!CollectionUtils.isEmpty(fragmentList)) { - map.values().forEach(path -> { - try { - Files.deleteIfExists(path); - } catch (IOException e) { - log.error("del fragment path:"+e); - } - }); - buildFragmentCSV(fragmentList); - } - } - } - } - log.warn("delAllFragment end"); - return ServerResponse.createBySuccess(); - } +// public ServerResponse delAllFragment() throws IOException { +// List botAccountPathList = Files.list(Paths.get("/root/TTS-service/audio")) +// .filter(path -> !StringUtils.startsWithAny(path.getFileName().toString(), "miao", "mqw", "test", "tmp")) +// .collect(Collectors.toList()); +// for (Path bpt: botAccountPathList) { +// List personPathList = Files.list(bpt).filter(path -> !StringUtils.equalsAny(path.getFileName().toString(), "xiaoai", "record")) +// .collect(Collectors.toList()); +// for (Path ppt: personPathList) { +// List moodPathList =Files.list(ppt).filter(path -> { +// boolean result = Files.isDirectory(path); +// if (!result) { +// try { +// Files.deleteIfExists(path); +// } catch (IOException e) { +// log.error("error:"+e); +// } +// } +// return result; +// }).collect(Collectors.toList()); +// for (Path mpt: moodPathList) { +// List mp3WavPathList = Files.list(mpt).filter(path -> !Files.isDirectory(path) && +// StringUtils.endsWithAny(path.getFileName().toString(), ".wav", ".mp3")) +// .collect(Collectors.toList()); +// Map map = new HashMap<>(); +// String filename; +// for (Path mwpt: mp3WavPathList) { +// filename = mwpt.getFileName().toString(); +// filename = filename.substring(0, filename.indexOf(".")); +// if (map.remove(filename) == null) { +// map.put(filename, mwpt); +// } +// } +// List fragmentList = map.values().stream().map(path -> path.toAbsolutePath().toString()).collect(Collectors.toList()); +// if (!CollectionUtils.isEmpty(fragmentList)) { +// map.values().forEach(path -> { +// try { +// Files.deleteIfExists(path); +// } catch (IOException e) { +// log.error("del fragment path:"+e); +// } +// }); +// buildFragmentCSV(fragmentList); +// } +// } +// } +// } +// log.warn("delAllFragment end"); +// return ServerResponse.createBySuccess(); +// } - private void buildFragmentCSV(List fragmentList) { - CSVFormat format; - if (Files.exists(Paths.get("/root/TTS-service/fragment_del.csv"))) format = CSVFormat.DEFAULT; - else format = CSVFormat.DEFAULT.withHeader("path"); - try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter( - new FileOutputStream("/root/TTS-service/fragment_del.csv", true), Charset.forName("UTF-8")),format)){ - for (String s: fragmentList) { - csvPrinter.printRecord(s); - } - } catch (IOException e) { - log.error("buildFragmentCSV error:"+e); - } - } +// private void buildFragmentCSV(List fragmentList) { +// CSVFormat format; +// if (Files.exists(Paths.get("/root/TTS-service/fragment_del.csv"))) format = CSVFormat.DEFAULT; +// else format = CSVFormat.DEFAULT.withHeader("path"); +// try (CSVPrinter csvPrinter = new CSVPrinter(new OutputStreamWriter( +// new FileOutputStream("/root/TTS-service/fragment_del.csv", true), Charset.forName("UTF-8")),format)){ +// for (String s: fragmentList) { +// csvPrinter.printRecord(s); +// } +// } catch (IOException e) { +// log.error("buildFragmentCSV error:"+e); +// } +// } // @PostMapping("/api/upload/record/one_npc") // public void uploadOneNpc(MultipartFile file, String botName, String npcName, @@ -449,6 +475,12 @@ public class TTSController { ttService.delOneSen(data, response, autho, groupId, botAccount); } + /** + * 删除某作品某语音人物某情绪除wav文件外的全部音频文件,创作平台试音台使用 + * @param mood 情绪 + * @param person 语音人物 + * @param botAccount 作品 + */ @DeleteMapping("/api/delete/one/person") public void deleteOnePerson(String mood, String person, String botAccount) { if (StringUtils.isAnyBlank(person, mood, botAccount)) { @@ -471,11 +503,21 @@ public class TTSController { // log.info("deleteOnePerson file not exist:"+pt.toAbsolutePath().toString()); } + /** + * 删除某个语音的wav,mp3和b64文件 + * @param text 文本 + * @param npcName 角色名 + * @param mood 情绪 + * @param person 语音人物 + * @param botAccount 作品 + * @param secret 密码 + */ @DeleteMapping("/api/delete/one/audio") public void delOneParticularAudio(String text, String npcName, String mood, String person, String botAccount, String secret) { if (StringUtils.startsWith(secret, "qiwu") && secret.length() == 8) { String fileName = TTSUtils.buildMP3Filename(text); + // 人工语音文件 if (StringUtils.isBlank(mood)) { String path = Initialize.AUDIO_DIR+File.separator+botAccount +File.separator+Initialize.UPLOADED_DIR+File.separator+npcName+File.separator+fileName; @@ -486,6 +528,7 @@ public class TTSController { } } else { + // 非人工语音文件 String pathPrefix = Initialize.AUDIO_DIR+File.separator+botAccount +File.separator+person+File.separator+mood+File.separator; try { @@ -509,16 +552,31 @@ public class TTSController { ttService.offlineCallback(file, response); } + /** + * 更新猎户语音token + * @param secret 调用接口密码 + */ @GetMapping("/api/update/Liehu") public void updateToken(String secret) { if ("miao".equals(secret)) lieHuSchedule.scheduleLieHuToken(); } + /** + * 专门用于音箱代码获取语音访问链接的接口 + * @param data + * @return + */ @PostMapping("/api/audio") public String apiAudio(@RequestBody ApiAudioData data) { return ttServiceEdition2.apiAudio(data); } + /** + * 获取音频文件数据接口 + * @param type 不为空则是小爱类型请求(合并音频) + * @param path 路径 + * @param response HttpServletResponse + */ @GetMapping("/api/audio/get") public void apiAudioGet(@RequestParam(required = false) String type, @RequestParam String path, HttpServletResponse response) { @@ -526,12 +584,26 @@ public class TTSController { ttService.apiAudioGetNoRange(type, path, response); } + /** + * 除音箱外其他平台多通过该接口获取音频数据,botAccount放在路径中,方便在cdn中整个删除该作品的全部音频 + * @param botAccount 作品 + * @param filename 文件路径 音频是否已存在,用于优化 + * @param exist 音频是否已存在,用于优化 + * @param response HttpServletResponse + */ @GetMapping("/api/audio/cache/{botAccount}/") public void apiAudioGetCacheDir(@PathVariable String botAccount, @RequestParam String filename, @RequestParam(required = false) Integer exist, HttpServletResponse response) { ttService.cdnAudioGet(filename, exist, response); } + /** + * 用于创作平台试音台或离线语音试听或角色声音试听那获取音频文件数据使用 + * @param exist 文件是否已存在,用于优化使用 + * @param _type 为file 代表下载音频文件 + * @param filename 文件路径 + * @param response HttpServletResponse + */ @GetMapping("/api/audio/tts") public void apiTTSAudioGet(@RequestParam(required = false) Integer exist, @RequestParam(required = false) String _type, @RequestParam String filename, HttpServletResponse response) { diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java index fc7398a..757c508 100644 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/Dialog.java @@ -14,6 +14,7 @@ import java.io.File; @Getter @Setter public class Dialog { + // 作品 角色名 语音人物名 文本 情绪 private String botAccount; private String npcName; private String person; diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java index 8595b75..687e4a9 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSLSRequest.java @@ -16,10 +16,10 @@ import java.util.List; @ToString @JsonIgnoreProperties(ignoreUnknown = true) public class TTSLSRequest { - private String _type; - private String platform; - private List text_info_ls; - private String botname; - private String person; - private Integer gen3rd; + private String _type; // 等与 filename 时代表只是获取音频的文件名 + private String platform; // 等与 xiaoai 时代表要将请求的多条文本的音频合并为一个文件,放到 xx/botAccount/xiaoai/ 目录下 + private List text_info_ls; // 请求的多个文本数据 + private String botname; // 作品id + private String person; // 语音角色名 + private Integer gen3rd; // // 第三方语音是否生成,为0则代表不处理该第三方语音 } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java index 7d54e56..00ec1cb 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TTSRequest.java @@ -14,14 +14,17 @@ import lombok.*; @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) public class TTSRequest { - private String person; - private String text; - private String _type; - private String pitch; - private String tone; - private String botname; + private String person; // 语音角色 + private String text; // 文本 + private String _type; // 为json时代表请求要获取的是音频访问链接 + private String tone; // 情绪 + private String botname; // 作品id + // 是否要获取线上地址,每个线下角色语音都有一个对应的线上角色, + // 在该请求获取不到时会跳转到其线上角色,这个参数控制是否跳转,false代表不 + private Boolean get_online; + private String npcName; // 角色名,指的是与作品相关的角色名称,用于寻找人工语音 + private String volume; private String speed; - private Boolean get_online; - private String npcName; + private String pitch; } diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java index e7a308f..ceeba83 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java @@ -18,12 +18,12 @@ import java.net.URLEncoder; @Setter @JsonIgnoreProperties(ignoreUnknown = true) public class TextInfo { - private String person; - private String text; - private String tone; - private String volume; - private String pitch; - private String speed; + private String person; //语音角色 + private String text; // 文本 + private String tone; // 情绪 + private String volume; // 音量 + private String pitch; // 语调 + private String speed; // 语速 private Boolean cache; private String server; private String botname; 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 003b891..7dc705f 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 @@ -43,6 +43,13 @@ import static ai.qiwu.com.tts_service.service.TTService.POOL; public class TTServiceEdition2 { private final StringRedisTemplate stringRedisTemplate; + /** + * 获取目标音频文件访问地址,第三方或系统合成语音目录如下 xx/botAccount/person/mood/,人工语音目录:xx/botAccount/npcName/ + * 多个音频合并后文件放置目录 xx/botAccount/xiaoai/ + * @param ttsRequest + * @param requestMethod + * @param servletResponse + */ public void tts(TTSRequest ttsRequest, String requestMethod, HttpServletResponse servletResponse) { // text字段不能为空 String text = ttsRequest.getText(); @@ -59,7 +66,8 @@ public class TTServiceEdition2 { if (StringUtils.isBlank(mood)) mood = Initialize.init_tone; // 第三方请求的情绪置为"正常",非第三方的请求则获取其请求地址url boolean doesThirdPerson = Initialize.getThirdPartyTts().contains(person); - String moodUrl = null; + String moodUrl = null; // 获取音频地址,分为线上和线下两种地址 + // 非第三方语音要对请求的语音人物person和情绪mood进行校对 if (!doesThirdPerson) { // 请求person不存在直接返回 Map map; @@ -93,6 +101,8 @@ public class TTServiceEdition2 { // botname为空则赋予tmp String botName = ttsRequest.getBotname(); + // 是否是创作平台角色试音请求,该请求需要在每次试听后删除mp3文件, + // 因为要确保并发下每个用户试听音频的正确不冲突 boolean tmpRequest = false; if (StringUtils.isBlank(botName)) { botName = "tmp"; @@ -102,9 +112,10 @@ public class TTServiceEdition2 { // (audio_dir)/botname/person/mood目录 String botFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).toString(); - String fileName = TTSUtils.buildMP3Filename(text); + String fileName = TTSUtils.buildMP3Filename(text); // 对文本加密获得其文件名称 String filePath; // (audio_dir)/botname/person/mood/xxx.mp3文件路径 + // 参数含有作品角色名参数则首先去寻找人工语音,人工语音优先 if (StringUtils.isNotBlank(npcName) && !"PUT".equals(requestMethod)) { String uploadedFilePath = StringUtils.join(new String[]{botFolder,Initialize.getUploadedDir(),npcName,fileName}, File.separator); if (TTSUtils.doesFileExist(uploadedFilePath)) { @@ -117,42 +128,51 @@ public class TTServiceEdition2 { } TTSResponse response = null; // _type为json,则构建请求get_audio接口的信息 + // 文件不存在或是PUT请求(重新合成mp3文件)时为true boolean shouldGenerateMp3 = !TTSUtils.doesFileExist(filePath) || "PUT".equals(requestMethod); + // type为json时代表请求要获取的是音频访问url if ("json".equals(ttsRequest.get_type())) { - String audioGetUrl; + String audioGetUrl; // 音频访问url地址 if (tmpRequest) { + // 试音请求文件名确保唯一 + // 23 指的是语音存放目录 /root/TTS-service/audio/ 的长度 fileName = RandomStringUtils.randomAlphabetic(3) + System.currentTimeMillis() + ".mp3"; audioGetUrl = filePath.substring(23, filePath.lastIndexOf(File.separator)+1)+fileName; } else { audioGetUrl = filePath.substring(23); } - //http://(server_url)/api/tts/get_audio?dirs=[botname+person,mood]&filename=xxx.mp3 + // 编码使得url符合规范 try { audioGetUrl = URLEncoder.encode(audioGetUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("URLEncoding编码出错:{},path:{}", e.toString(),audioGetUrl); } + //exist字段用于优化get访问时,告知get接口该文件已存在 if (shouldGenerateMp3) audioGetUrl += "&exist=1"; audioGetUrl = Initialize.getServerUrl()+"/api/audio/tts?filename="+audioGetUrl; response = new TTSResponse(audioGetUrl,HttpServletResponse.SC_OK); } - boolean generate = true; - boolean setSuccess = false; + boolean generate = true; // 音频文件是否之前已存在 + boolean setSuccess = false; // 锁,确保并发下同一作品角色情绪的文本合成不冲突, // filepath文件不存在或是put请求,调用generalMP3生成该filepath所指的mp3文件 if (shouldGenerateMp3){ generate = false; GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), ttsRequest.getText(), person, mood, botName, true, volume, speed, pitch); data.setNpcName(npcName); - if (tmpRequest) data.setTmpName(fileName); + if (tmpRequest) data.setTmpName(fileName); // 角色试音类请求filename不同与其他 try { + // 上锁 if ((setSuccess=Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(filePath, "1", 40, TimeUnit.SECONDS)))) { + // 合成音频 ResponseCodeWithData codeWithData = generalMP3(moodUrl, data, filePath, requestMethod, getOnline); + // 合成出错 if (codeWithData == null) { TTServiceUtil.buildServletResponse(servletResponse, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } if (codeWithData.getCode() != HttpServletResponse.SC_OK) { + // 打印失败信息 if (codeWithData.getCode() == HttpServletResponse.SC_NOT_FOUND) { log.info("404,请求地址不存在"); }else { @@ -169,9 +189,12 @@ public class TTServiceEdition2 { if (setSuccess) stringRedisTemplate.delete(filePath); } } + // 音频文件准备成功 if (response == null) { + // 文件已存在/当前请求下载音频成功 if (generate || setSuccess) TTServiceUtil.buildServletResponse(servletResponse, null, new File(filePath), HttpServletResponse.SC_OK); else { + // 竞争请求需等待获取锁请求准备音频文件成功 int count = 0; while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(filePath)) && count < 10) { try { @@ -194,10 +217,18 @@ public class TTServiceEdition2 { } } + /** + * 获取音频文件数据 + * @param filename 相对地址 + * @param exist 是否已存在 + * @param _type 等与file时代表要下载文件 + * @param response HttpServletResponse + */ public void ttsAudioGet(String filename, Integer exist, String _type, HttpServletResponse response) { - boolean tmp = StringUtils.startsWith(filename, "/tmp"); + boolean tmp = StringUtils.startsWith(filename, "/tmp"); // /tmp开头代表是创作平台角色试音类型请求,需要在文件数据传输后删除该文件 + // 请求mp3数据 if (StringUtils.endsWith(filename,".mp3")) { - String filepath = Initialize.AUDIO_DIR + filename; + String filepath = Initialize.AUDIO_DIR + filename; //绝对地址 Path pt = Paths.get(filepath); // exist == null 表明调用时确定已存在 if (exist == null) { @@ -208,6 +239,7 @@ public class TTServiceEdition2 { } else { TTServiceUtil.buildTTSMp3Response(response, null, filepath, HttpServletResponse.SC_OK, false); } + // 创作平台角色试音类型请求,需要在文件数据传输后删除该文件 if (tmp) { POOL.submit(() -> { if (!new File(filepath).delete()) log.info("ttsAudioGet 删除tmp文件失败:{}",filepath); @@ -218,8 +250,10 @@ public class TTServiceEdition2 { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } else { + // 由于音频文件下载是异步的,导致访问时文件可能未合成完毕,判断条件是redis中的锁是否存在 int count = 0; boolean fileExist; + // 文件是否存在不能代表音频文件数据是否下载完成,以redis锁为准 while (!(fileExist=Files.exists(pt)) && count < 16) { try { Thread.sleep(500); @@ -231,6 +265,7 @@ public class TTServiceEdition2 { log.warn("ttsAudioGet 等待8s后音频文件仍不存在:"+filename); return; } + // 判断锁 while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(filename))&& count < 30) { try { Thread.sleep(500); @@ -261,11 +296,16 @@ public class TTServiceEdition2 { } } + /** + * 一次请求多个文本的音频 + * @param request 请求数据 + * @param response HttpServletResponse + */ public void tts_ls(TTSLSRequest request, HttpServletResponse response) { // long start = System.currentTimeMillis(); - String _type = request.get_type(); - String platform = request.getPlatform(); + String _type = request.get_type(); // 等与 filename 时代表只是获取音频的文件名 + String platform = request.getPlatform(); // 与 xiaoai 时代表要将请求的多条文本的音频合并为一个文件 List infoList = request.getText_info_ls(); // botname不能为空 String botName = request.getBotname(); @@ -274,12 +314,16 @@ public class TTServiceEdition2 { TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_BAD_REQUEST, "no botname"), null, HttpServletResponse.SC_BAD_REQUEST); return; } + // 各个文本合成结果列表 List> futures = new ArrayList<>(); List file_ls = new ArrayList<>(); + // 到作品id为止的根目录 String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString(); + // 人工语音根目录,xx/botName/record/ String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString(); // 第三方语音是否生成,为0则代表不处理该第三方语音 boolean geneThird = request.getGen3rd() == null || request.getGen3rd() != 0; + // 处理文本数据列表 if (infoList != null && infoList.size() != 0) { for (TextInfo info : infoList) { // String beforeCache; @@ -289,6 +333,9 @@ public class TTServiceEdition2 { // file_ls.add(beforeCache); // continue; // } + + // 通过作品id判断文本所属作品是否与最外层作品是同一作品 + // 不相同时以文本作品id为准,重新构建路径 String uploadFolder, rootFolder; if (botName.equals(info.getBotAccount()) || StringUtils.isBlank(info.getBotAccount())) { rootFolder = rootFolderRoot; @@ -307,7 +354,7 @@ public class TTServiceEdition2 { String text = info.getText(); if (StringUtils.isBlank(text)) continue; - String url = null; //moodUrl + String url = null; //moodUrl 音频下载链接分为线上和线下不同地址 String tone = DEFAULT_MOOD; // 第三方请求的情绪为:正常 // 是否是第三方请求 @@ -352,19 +399,24 @@ public class TTServiceEdition2 { } // if (!TTSUtils.doesFileExist(filepath) && !botName.equals("550829152")) { + // 文件不存在去下载 if (!TTSUtils.doesFileExist(filepath)) { final GeneralMP3Data data = new GeneralMP3Data(Initialize.getServerName(), text, person, tone, botName, true, volume, speed, pitch); data.setNpcName(npcName); final String path = filepath; final String moodUrl = url; + // 异步 Future future = POOL.submit(() -> { int waitTime = 40; - if (isPersonThirdParty) waitTime = 45; + if (isPersonThirdParty) waitTime = 45; // 延长第三方语音请求的最大等待时间 + // 下载前先上锁,避免竞争 if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(path, "1", waitTime, TimeUnit.SECONDS))) { // log.info("future generate:{},text:{}",path,text); try { + // double check 确保文件一定不存在 if (!TTSUtils.doesFileExist(path)) { + // 生成音频文件 ResponseCodeWithData response1 = generalMP3(moodUrl, data, path, "GET",true); if (response1 == null) response1 = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "tts_ls:generalMP3 return null"); // if (response1.getCode() == 200) { @@ -380,7 +432,7 @@ public class TTServiceEdition2 { } return new ResponseCodeWithData(8, path); }); - futures.add(future); + futures.add(future); // 结果存进结果集中 } // _type为filename则说明请求要获取的是.b64文件名列表,platform字段优先级高于_type @@ -388,12 +440,14 @@ public class TTServiceEdition2 { filepath = filepath+".b64"; } } else { + // 不合成的第三方请求以特殊字段代替 filepath = Initialize.getThirdParty(); } - file_ls.add(filepath); + file_ls.add(filepath); // 该文本语音的地址存储进集合 } boolean xiaoai; + // 无需同步等待下载完成的请求都走异步 if ((xiaoai="xiaoai".equals(platform)) || !StringUtils.endsWith(_type, "64")) { // 异步合成b64文件 final String finalBotName = botName; @@ -423,6 +477,15 @@ public class TTServiceEdition2 { // } // } + /** + * 根据请求参数下载合成音频文件 + * @param url 离线/在线音频请求地址 + * @param data 参数信息 + * @param filePath 文件地址 + * @param requestMethod PUT 请求特殊处理,代表即使mp3文件存在也要重新利用wav文件生成新的mp3文件,替代旧的 + * @param getOnline 连线语音角色下载返回404时会跳转到其对应的在线角色去请求,该参数控制是否跳转 + * @return ResponseCodeWithData + */ private ResponseCodeWithData generalMP3(String url, GeneralMP3Data data, String filePath, String requestMethod, boolean getOnline) { ResponseCodeWithData res = null; @@ -432,6 +495,7 @@ public class TTServiceEdition2 { log.error("generalMP3 目录创建失败:{},msg:{}",filePath,e); return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } + // mp3文件都是从wav转换过来的所以先去处理wav文件情况 String wavFilename = filePath.substring(0, filePath.length()-4)+".wav"; //对于请求参数中带有npcName的,首先判断其是否是分段请求,即检查text中是否包含AB符号 if (StringUtils.isNotBlank(data.getNpcName())) { @@ -444,7 +508,7 @@ public class TTServiceEdition2 { if (res.getCode() != HttpServletResponse.SC_OK) return res; } else { data.setFormat("wav"); - res = requestTemplate(url, data, wavFilename, getOnline); + res = requestTemplate(url, data, wavFilename, getOnline); // 下载我们自己的系统音wav文件 if (res == null || res.getCode() != HttpServletResponse.SC_OK) { log.error("generalMP3 下载wav失败:{}, 响应信息:{}",wavFilename,res); return res; @@ -455,6 +519,8 @@ public class TTServiceEdition2 { return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } + // wav存在后,需要根据参数调用python转换代码将其转成mp3文件 + // 对于put请求则直接讲wav转为mp3,其他则先判断mp3文件是否存在, // 不存在对于线下请求则去url地址下载该mp3文件,线上的则直接转wav boolean fileExist = TTSUtils.doesFileExist(filePath); @@ -462,10 +528,12 @@ public class TTServiceEdition2 { if (fileExist) { new File(filePath).delete(); } - // 试听生成的临时mp3文件名 + // 创作平台角色语音试听类请求,生成临时mp3文件名 if (data.getTmpName() != null) filePath = filePath.substring(0, filePath.lastIndexOf(File.separator)+1)+data.getTmpName(); + // wav转mp3 res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); } else if (!fileExist) { + // 对于离线语音角色的mp3在不存在时先去下载,不成共再wav转; 在线之间wav转 if (Initialize.OFFLINE_SERVER.equals(url)) { data.setFormat("mp3"); // int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath); @@ -479,22 +547,34 @@ public class TTServiceEdition2 { res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); } }else { + // wav转mp3 res = changeSound(wavFilename, data.getVolume(), data.getSpeed(), data.getPitch(), filePath); } } - if (res == null) res = new ResponseCodeWithData(HttpServletResponse.SC_OK); + if (res == null) res = new ResponseCodeWithData(HttpServletResponse.SC_OK);// res == null代表成功 return res; } + /** + * 处理下载wav文件请求 + * @param url 下载地址 + * @param data 请求参数 + * @param filePath 文件地址 + * @param getOnline 离线语音角色下载返回404后是否允许跳转到其线上角色 + * @return ResponseCodeWithData + */ private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean getOnline) { ResponseCodeWithData res; // data.setMode("test"); String dataJsonStr; + // 下载wav请求 int status = OkHttp3Utils.postTTSEdition2(url, Collections.emptyMap(), (dataJsonStr=JSON.toJSONString(data)), filePath, false); // int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath); + // 离线语音角色下载返回404,跳转到其线上角色 if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) { res = dealOfflineJump(data, getOnline, filePath); } else if (status != HttpServletResponse.SC_OK){ + // 其他情况下载不成功则最多重复请求三次,次与次之间间隔递增 int retryCount = 0; do { retryCount++; @@ -521,13 +601,22 @@ public class TTServiceEdition2 { return res; } + /** + * 处理离线下载404跳转线上情况 + * @param data 数据 + * @param getOnline 控制是否跳转 + * @param filePath 文件地址 + * @return ResponseCodeWithData + */ private ResponseCodeWithData dealOfflineJump(GeneralMP3Data data, boolean getOnline, String filePath) { if (!getOnline) return new ResponseCodeWithData(HttpServletResponse.SC_NOT_FOUND, "没有找到该文件"); + // 获取该离线角色对应的在线角色 List list = Initialize.getTheOfflineJumpPersonInfo(data.getPerson(), data.getTone()); GeneralMP3Data jumpedData = new GeneralMP3Data(data.getServer(), data.getText(), list.get(0), list.get(1), data.getBotname(), data.getCache(), data.getVolume(), data.getSpeed(), data.getPitch()); log.warn("线下人物请求404,跳转到其对应的线上人物:人物:{}->{},情绪:{}->{}",data.getPerson(),jumpedData.getPerson(),data.getTone(), jumpedData.getTone()); // int status = ApachHttpUtils.audioPost(Initialize.AUDIO_GENERATE_SERVER, JSON.toJSONString(jumpedData), filePath); + // 下载 int status = OkHttp3Utils.postTTSEdition2(Initialize.AUDIO_GENERATE_SERVER, Collections.emptyMap(), JSON.toJSONString(jumpedData), filePath, false); return new ResponseCodeWithData(status); } @@ -556,6 +645,15 @@ public class TTServiceEdition2 { // return res; // } + /** + * 调用python代码讲wav文件转换成mp3文件 + * @param wavFilename wav文件 + * @param volume 音量 + * @param speed 语速 + * @param pitch 语调 + * @param mp3FilePath mp3 文件地址 + * @return ResponseCodeWithData + */ private ResponseCodeWithData changeSound(String wavFilename, double volume, double speed, double pitch, String mp3FilePath) { ResponseCodeWithData res = null; @@ -573,34 +671,55 @@ public class TTServiceEdition2 { return res; } + /** + * 处理分段文本, 比如"请问你们要买什么🅰蔬菜🅱 ",🅰 和 🅱 之间的部分是变量,其余是非变量 + * @param url 离线/在线语音请求地址 + * @param data 数据 + * @param personToneFilePath 文件地址 + * @param requestMethod PUT请求特殊处理 + * @param getOnline 是否允许跳转线上 + * @return 返回true代表该分段文本处理完成 + */ private boolean genRecordWithChangeEdition2(String url, GeneralMP3Data data, String personToneFilePath, String requestMethod, boolean getOnline) { String text = data.getText(); + // 🅰的unicode编码就是\uD83C\uDD70,不是分段文本返回false if (!text.contains("\uD83C\uDD70")) { return false; } + //将分段文本拆分,确保顺序正确 List splitList = new ArrayList<>(); String[] arr = text.split("\uD83C\uDD70"); for (String item: arr) { splitList.addAll(Arrays.asList(item.split("\uD83C\uDD71"))); } + // 片段文本的音频数据异步下载结果集 List> asynResultList = new ArrayList<>(splitList.size()); + // 收集出现竞争情况的文本音频地址集合 List conditionPathList = new ArrayList<>(splitList.size()); + // 人工语音根地址,人工语音优先级高于其他 String recordFolder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotname(), Initialize.getUploadedDir(), data.getNpcName()}, File.separator); + // 非人工语音根地址 String usDir = StringUtils.join(new String[]{Initialize.getAudioDir(),data.getBotname(), data.getPerson(), data.getTone()}, File.separator); + // 按顺序处理各个片段文本 splitList = splitList.stream().filter(s -> StringUtils.isNotBlank(s.replaceAll("\\p{P}", ""))) .map(s -> { String filename; + // 音频地址,人工语义优先探测 String filepath = new StringBuilder(recordFolder).append(File.separator) .append((filename=TTSUtils.buildMP3Filename(s))).toString(); if (!TTSUtils.doesFileExist(filepath)) { + // 人工不存在找寻合成音/第三方语音 filepath = new StringBuilder(usDir).append(File.separator).append(filename).toString(); if (!TTSUtils.doesFileExist(filepath)) { + // 下载前先获取该片段文本的处理锁 if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(filepath, "1", 30, TimeUnit.SECONDS))) { + // Double check if (!TTSUtils.doesFileExist(filepath)) { final String finalPath = filepath; + //异步处理文本音频合成操作 Future result = POOL.submit(() -> { try { GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), s,data.getPerson(), @@ -612,12 +731,12 @@ public class TTServiceEdition2 { stringRedisTemplate.delete(finalPath); } }); - asynResultList.add(result); + asynResultList.add(result); // Future加入结果集 } else { stringRedisTemplate.delete(filepath); } } else { - conditionPathList.add(filepath); + conditionPathList.add(filepath); // 收集出现竞争情况的文本音频地址 } } } @@ -625,6 +744,7 @@ public class TTServiceEdition2 { }).collect(Collectors.toList()); try { + // 等待直到所有片段都下载完成 if (asynResultList.size() != 0) { String result; try { @@ -637,6 +757,7 @@ public class TTServiceEdition2 { return false; } } + // 对于竞争情况需等待目标文件下载完成,即redis锁消失 if (conditionPathList.size() != 0) { for (String conditionPath: conditionPathList) { int co = 0; @@ -654,6 +775,8 @@ public class TTServiceEdition2 { } } // long start = System.currentTimeMillis(); + + // 将所有片段语音按顺序合并成一个 TTSUtils.combineMp3File(splitList, personToneFilePath, false); // log.warn("拼接耗时:{}->{}",personToneFilePath,(System.currentTimeMillis()-start)); if (!new File(personToneFilePath).exists()) { @@ -667,201 +790,211 @@ public class TTServiceEdition2 { return true; } - private boolean genRecordWithChange(String url, GeneralMP3Data data, String personToneFilePath, - String requestMethod, boolean getOnline) { - final String text = data.getText(); - // 存储变量集合 - List variableTextList = new ArrayList<>(); - // 获取AB之间的变量,为空则忽略 - Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); - Matcher matcher = pattern.matcher(text); - while (matcher.find()) { - String variableText = matcher.group(1); - if (StringUtils.isNotBlank(variableText)) variableTextList.add(variableText); - } - //log.info("variableTextList:{}",variableTextList); - //不是分段语句则返回false,回到generalMP3方法整体处理 - if (variableTextList.size() != 0) { -// log.info("第三方请求文本:botaccount:{},text:{},path:{}",data.getBotname(), text, personToneFilePath); - // 要合并的mp3地址集合 - TreeMap combineMp3Text2FilePath = new TreeMap<>(Comparator.comparingInt(text::indexOf)); - // 人工上传目录, audio_dir/botname/record/npcname - String recordFolder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotname(), - Initialize.getUploadedDir(), data.getNpcName()}, File.separator); - // 语音合成目录;audio_dir/botname/person/tone - String usDir = StringUtils.join(new String[]{Initialize.getAudioDir(),data.getBotname(), - data.getPerson(), data.getTone()}, File.separator); - // 非变量部分 - String[] notVariableTextArray = pattern.split(text); - //log.info("notVariableTextArray:{}",Arrays.toString(notVariableTextArray)); - // 遍历所有非变量,若其mp3文件在人工目录下不存在则返回false回到generalMp3方法,整句合成 - int i = 0; - List> asynResultList = null; - List conditionPathList = null; // 竞争音频路径列表 - for (String notVariableText: notVariableTextArray) { - if (StringUtils.isBlank(notVariableText)) { - ++i; - continue; - } - if (i++ == notVariableTextArray.length-1) { - boolean notVariableLast = text.lastIndexOf(notVariableText)+notVariableText.length() == text.length(); - if (notVariableLast) { - String last = notVariableText; - last = last.replaceAll("\\p{P}", ""); - if (StringUtils.isBlank(last)) { - //log.info("last is empty"); - break; - } - } - } - String filename; - String notVariableTextPath = new StringBuilder(recordFolder).append(File.separator) - .append((filename=TTSUtils.buildMP3Filename(notVariableText))).toString(); - //log.info("notVariableTextPath:{}",notVariableTextPath); - if (!TTSUtils.doesFileExist(notVariableTextPath)) { - if ("Liehu1".equals(data.getPerson())) return false; - String thirdPath = new StringBuilder(usDir).append(File.separator).append(filename).toString(); - if (!TTSUtils.doesFileExist(thirdPath)) { - if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(thirdPath, "1", 30, TimeUnit.SECONDS))) { - if (!TTSUtils.doesFileExist(thirdPath)) { - if (notVariableTextArray.length == 1) { - try { - GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), notVariableText,data.getPerson(), - data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); - ResponseCodeWithData response = generalMP3(url, variableData, thirdPath, requestMethod, getOnline); - if (response == null || response.getCode() != 200) return false; - } finally { - stringRedisTemplate.delete(thirdPath); - } - } else { - if (asynResultList == null) asynResultList = new ArrayList<>(notVariableTextArray.length); - Future result = POOL.submit(() -> { - try { - GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), notVariableText,data.getPerson(), - data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); - ResponseCodeWithData response = generalMP3(url, variableData, thirdPath, requestMethod, getOnline); - if (response == null || response.getCode() != 200) return "0"; - return "1"; - } finally { - stringRedisTemplate.delete(thirdPath); - } - }); - asynResultList.add(result); - } - } else { - stringRedisTemplate.delete(thirdPath); - } - } else { - if (conditionPathList == null) conditionPathList = new ArrayList<>(notVariableTextArray.length); - conditionPathList.add(thirdPath); - } - } - notVariableTextPath = thirdPath; -// if (Initialize.getThirdPartyTts().contains(data.getPerson())) { +// private boolean genRecordWithChange(String url, GeneralMP3Data data, String personToneFilePath, +// String requestMethod, boolean getOnline) { +// final String text = data.getText(); +// // 存储变量集合 +// List variableTextList = new ArrayList<>(); +// // 获取AB之间的变量,为空则忽略 +// Pattern pattern = Pattern.compile(TTSUtils.getAbRegex()); +// Matcher matcher = pattern.matcher(text); +// while (matcher.find()) { +// String variableText = matcher.group(1); +// if (StringUtils.isNotBlank(variableText)) variableTextList.add(variableText); +// } +// //log.info("variableTextList:{}",variableTextList); +// //不是分段语句则返回false,回到generalMP3方法整体处理 +// if (variableTextList.size() != 0) { +//// log.info("第三方请求文本:botaccount:{},text:{},path:{}",data.getBotname(), text, personToneFilePath); +// // 要合并的mp3地址集合 +// TreeMap combineMp3Text2FilePath = new TreeMap<>(Comparator.comparingInt(text::indexOf)); +// // 人工上传目录, audio_dir/botname/record/npcname +// String recordFolder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotname(), +// Initialize.getUploadedDir(), data.getNpcName()}, File.separator); +// // 语音合成目录;audio_dir/botname/person/tone +// String usDir = StringUtils.join(new String[]{Initialize.getAudioDir(),data.getBotname(), +// data.getPerson(), data.getTone()}, File.separator); +// // 非变量部分 +// String[] notVariableTextArray = pattern.split(text); +// //log.info("notVariableTextArray:{}",Arrays.toString(notVariableTextArray)); +// // 遍历所有非变量,若其mp3文件在人工目录下不存在则返回false回到generalMp3方法,整句合成 +// int i = 0; +// List> asynResultList = null; +// List conditionPathList = null; // 竞争音频路径列表 +// for (String notVariableText: notVariableTextArray) { +// if (StringUtils.isBlank(notVariableText)) { +// ++i; +// continue; +// } +// if (i++ == notVariableTextArray.length-1) { +// boolean notVariableLast = text.lastIndexOf(notVariableText)+notVariableText.length() == text.length(); +// if (notVariableLast) { +// String last = notVariableText; +// last = last.replaceAll("\\p{P}", ""); +// if (StringUtils.isBlank(last)) { +// //log.info("last is empty"); +// break; +// } +// } +// } +// String filename; +// String notVariableTextPath = new StringBuilder(recordFolder).append(File.separator) +// .append((filename=TTSUtils.buildMP3Filename(notVariableText))).toString(); +// //log.info("notVariableTextPath:{}",notVariableTextPath); +// if (!TTSUtils.doesFileExist(notVariableTextPath)) { +// if ("Liehu1".equals(data.getPerson())) return false; +// String thirdPath = new StringBuilder(usDir).append(File.separator).append(filename).toString(); +// if (!TTSUtils.doesFileExist(thirdPath)) { +// if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(thirdPath, "1", 30, TimeUnit.SECONDS))) { +// if (!TTSUtils.doesFileExist(thirdPath)) { +// if (notVariableTextArray.length == 1) { +// try { +// GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), notVariableText,data.getPerson(), +// data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); +// ResponseCodeWithData response = generalMP3(url, variableData, thirdPath, requestMethod, getOnline); +// if (response == null || response.getCode() != 200) return false; +// } finally { +// stringRedisTemplate.delete(thirdPath); +// } +// } else { +// if (asynResultList == null) asynResultList = new ArrayList<>(notVariableTextArray.length); +// Future result = POOL.submit(() -> { +// try { +// GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), notVariableText,data.getPerson(), +// data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); +// ResponseCodeWithData response = generalMP3(url, variableData, thirdPath, requestMethod, getOnline); +// if (response == null || response.getCode() != 200) return "0"; +// return "1"; +// } finally { +// stringRedisTemplate.delete(thirdPath); +// } +// }); +// asynResultList.add(result); +// } +// } else { +// stringRedisTemplate.delete(thirdPath); +// } +// } else { +// if (conditionPathList == null) conditionPathList = new ArrayList<>(notVariableTextArray.length); +// conditionPathList.add(thirdPath); +// } +// } +// notVariableTextPath = thirdPath; +//// if (Initialize.getThirdPartyTts().contains(data.getPerson())) { +//// } else { +//// return false; +//// } +// } +// combineMp3Text2FilePath.put(notVariableText, notVariableTextPath); +// } +// // 遍历所有变量,若其mp3文件在人工目录下不存在则调用generalMP3方法生成 +// for (String variableText: variableTextList) { +// String variableTextFilename = TTSUtils.buildMP3Filename(variableText); +// String variableTextPath = new StringBuilder(recordFolder).append(File.separator) +// .append(variableTextFilename).toString(); +// if (!TTSUtils.doesFileExist(variableTextPath)) { +// String variablePathInUsDir = new StringBuilder(usDir).append(File.separator).append(variableTextFilename).toString(); +// if (!TTSUtils.doesFileExist(variablePathInUsDir)) { +// if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(variablePathInUsDir, "1", 30, TimeUnit.SECONDS))) { +// if (!TTSUtils.doesFileExist(variablePathInUsDir)) { +// if (variableTextList.size() == 1) { +// try { +// GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), +// data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); +// ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); +// if (response == null || response.getCode() != 200) return false; +// } finally { +// stringRedisTemplate.delete(variablePathInUsDir); +// } +// } else { +// if (asynResultList == null) asynResultList = new ArrayList<>(variableTextList.size()); +// Future result = POOL.submit(() -> { +// try { +// GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), +// data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); +// ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); +// if (response == null || response.getCode() != 200) return "0"; +// return "1"; +// } finally { +// stringRedisTemplate.delete(variablePathInUsDir); +// } +// }); +// asynResultList.add(result); +// } +// } else { +// stringRedisTemplate.delete(variablePathInUsDir); +// } +// } // } else { +// if (conditionPathList == null) conditionPathList = new ArrayList<>(variableTextList.size()); +// conditionPathList.add(variablePathInUsDir); +// } +// variableTextPath = variablePathInUsDir; +// } +// combineMp3Text2FilePath.put(variableText, variableTextPath); +// } +// // 合并所有分段mp3文件 +// try { +// if (asynResultList != null) { +// String result; +// try { +// for (Future future : asynResultList) { +// result = future.get(40, TimeUnit.SECONDS); +// if ("0".equals(result)) return false; +// } +// } catch (Exception e) { +// log.error("获取分段响应结果出错:{},text:{}",e,text); // return false; // } - } - combineMp3Text2FilePath.put(notVariableText, notVariableTextPath); - } - // 遍历所有变量,若其mp3文件在人工目录下不存在则调用generalMP3方法生成 - for (String variableText: variableTextList) { - String variableTextFilename = TTSUtils.buildMP3Filename(variableText); - String variableTextPath = new StringBuilder(recordFolder).append(File.separator) - .append(variableTextFilename).toString(); - if (!TTSUtils.doesFileExist(variableTextPath)) { - String variablePathInUsDir = new StringBuilder(usDir).append(File.separator).append(variableTextFilename).toString(); - if (!TTSUtils.doesFileExist(variablePathInUsDir)) { - if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue().setIfAbsent(variablePathInUsDir, "1", 30, TimeUnit.SECONDS))) { - if (!TTSUtils.doesFileExist(variablePathInUsDir)) { - if (variableTextList.size() == 1) { - try { - GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), - data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); - ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); - if (response == null || response.getCode() != 200) return false; - } finally { - stringRedisTemplate.delete(variablePathInUsDir); - } - } else { - if (asynResultList == null) asynResultList = new ArrayList<>(variableTextList.size()); - Future result = POOL.submit(() -> { - try { - GeneralMP3Data variableData = new GeneralMP3Data(data.getServer(), variableText,data.getPerson(), - data.getTone(), data.getBotname(), data.getCache(),data.getVolume(),data.getSpeed(),data.getPitch()); - ResponseCodeWithData response = generalMP3(url, variableData, variablePathInUsDir, requestMethod, getOnline); - if (response == null || response.getCode() != 200) return "0"; - return "1"; - } finally { - stringRedisTemplate.delete(variablePathInUsDir); - } - }); - asynResultList.add(result); - } - } else { - stringRedisTemplate.delete(variablePathInUsDir); - } - } - } else { - if (conditionPathList == null) conditionPathList = new ArrayList<>(variableTextList.size()); - conditionPathList.add(variablePathInUsDir); - } - variableTextPath = variablePathInUsDir; - } - combineMp3Text2FilePath.put(variableText, variableTextPath); - } - // 合并所有分段mp3文件 - try { - if (asynResultList != null) { - String result; - try { - for (Future future : asynResultList) { - result = future.get(40, TimeUnit.SECONDS); - if ("0".equals(result)) return false; - } - } catch (Exception e) { - log.error("获取分段响应结果出错:{},text:{}",e,text); - return false; - } - } - if (conditionPathList != null) { - for (String conditionPath: conditionPathList) { - int co = 0; - while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(conditionPath)) && co++ < 10) { - try { - Thread.sleep(500); - } catch (Exception e) { - // do nothing - } - } - if (co == 11 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(conditionPath))) { - log.error("genRecordWithChange 分段遇到竞争等待5s对方仍未结束,"+conditionPath); - return false; - } - } - } -// long start = System.currentTimeMillis(); - TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath, false); -// log.warn("拼接耗时:{}->{}",personToneFilePath,(System.currentTimeMillis()-start)); - if (!new File(personToneFilePath).exists()) { - log.error("分段合并音频,未找到合并后的文件"); - return false; - } - } catch (Exception e) { - log.error("genRecordWithChange:合成音频失败:{}",e.toString()); - return false; - } - return true; - } - return false; - } +// } +// if (conditionPathList != null) { +// for (String conditionPath: conditionPathList) { +// int co = 0; +// while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(conditionPath)) && co++ < 10) { +// try { +// Thread.sleep(500); +// } catch (Exception e) { +// // do nothing +// } +// } +// if (co == 11 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(conditionPath))) { +// log.error("genRecordWithChange 分段遇到竞争等待5s对方仍未结束,"+conditionPath); +// return false; +// } +// } +// } +//// long start = System.currentTimeMillis(); +// TTSUtils.combineMp3File(combineMp3Text2FilePath.values(), personToneFilePath, false); +//// log.warn("拼接耗时:{}->{}",personToneFilePath,(System.currentTimeMillis()-start)); +// if (!new File(personToneFilePath).exists()) { +// log.error("分段合并音频,未找到合并后的文件"); +// return false; +// } +// } catch (Exception e) { +// log.error("genRecordWithChange:合成音频失败:{}",e.toString()); +// return false; +// } +// return true; +// } +// return false; +// } + /** + * 处理第三方语音下载请求 + * @param text 文本 + * @param person 人物 + * @param filepath 地址 + * @return ResponseCodeWithData + */ private ResponseCodeWithData dealThirdParty(String text, String person, String filepath) { // log.warn("dealThirdParty:text:{}, person:{}, filepath:{}", text, person, filepath); boolean result; // 去除所有{/../} // text = text.replaceAll("[\uD83C\uDD70\uD83C\uDD71]", "").trim(); + //首先判断是否存在标音符号 if (text.contains("{/")) { + // 根据前缀分类处理不同的第三方 + // 将我们自己平台的标音符号转换为各个平台规定的标音符号 String prefix = person.substring(0, 5); switch (prefix) { case "Baidu" : { @@ -870,7 +1003,10 @@ public class TTServiceEdition2 { break; } case "XunFe" : { + // 讯非有些角色适用SSML规范,有些存在简化标音方式,非类处理 if (Initialize.xunfeiUseSSMLPerson.contains(person)) { + // 代码作用是替换标音符号,讯非标音要求查看讯非文档 + // http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=15340 StringBuilder temp = new StringBuilder(); int sliceStart = 0; for (int i = 0; i < text.length()-1; i++) { @@ -946,12 +1082,15 @@ public class TTServiceEdition2 { // log.info("第三方请求文本:text:{},path:{}", text, filepath); // long start = System.currentTimeMillis(); // log.info("第三方TEXT:"+text); + + // 第三方下载类 result = ThirdPartyService.thirdPartyCall(text, Initialize.theThirdPartysPer(person), filepath, person); // log.info(person+"第三方请求耗时:"+(System.currentTimeMillis()-start)); if (result) { return new ResponseCodeWithData(HttpServletResponse.SC_OK, "创建第三方wav文件成功"); } + // 第三方下载失败最多重试3次,等待时间叠加 int thirdFailRetryCount = 0; do { thirdFailRetryCount++; @@ -968,6 +1107,12 @@ public class TTServiceEdition2 { return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "调用第三方生成wav文件失败"); } + /** + * 对于使用SSML规范标音的第三方语音,统一调用该方法进行替换 + * 要求查看阿里或腾讯的ssml文档 + * @param text + * @return + */ private String dealStandSSMLBiaoYin(String text) { StringBuilder temp = new StringBuilder(""); int sliceStart = 0; @@ -1011,16 +1156,30 @@ public class TTServiceEdition2 { return temp.toString(); } + /** + * 下载音频文件为异步操作,该方法就是处理异步的Future + * @param futures 异步 + * @param response HttpServletResponse + * @param file_ls 音频文件路径 + * @param xiaoai 是否需要合并所有音频为一个 + * @param botName 作品id + * @param asyn 是否异步,同步请求需要讲结果写图到HttpServletResponse中 + * @return + */ private boolean getFromFutureAndGenerateB64File(List> futures, HttpServletResponse response, List file_ls, boolean xiaoai, String botName, boolean asyn) { // 阻塞等待mp3文件生成成功 // if (futures.size() == 0) log.info("futures is empty"); + // 遍历处理异步结果集 for (Future future : futures) { try { ResponseCodeWithData data = future.get(6, TimeUnit.MINUTES); if (data.getCode() != HttpServletResponse.SC_OK) { + // 结果不成功的情况中有种是出现竞争情况的,此时code值为8 if (data.getCode() == 8) { log.info("tts_ls:出现竞争情况->"+data.getRes()); + // 出现竞争res字段值为路径,通过他来查锁 + // 首先判断文件是否下载完成即锁是否还存在,之后判断文件是否存在 if (data.getRes() != null) { int count = 0; while (Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes())) && count < 20) { @@ -1031,13 +1190,16 @@ public class TTServiceEdition2 { } ++count; } + // 等待超时 if (count == 20 && Boolean.TRUE.equals(stringRedisTemplate.hasKey(data.getRes()))) { log.warn("tts_ls:10s后竞争者仍未完成音频操作->"+data.getRes()); if (!asyn) TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), null, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } + // 文件是否存在 if (!TTSUtils.doesFileExist(data.getRes())) { + // count 为叠加变量,保证总等待时间大小 if (count < 20) { log.warn("竞争但是 redis 没有该键,文件却不存在:"+data.getCode()); do { @@ -1075,14 +1237,20 @@ public class TTServiceEdition2 { } } + // 结果获取完毕,全部文本都已合成结束 + + // 为true则代表要将音频合并为一个 if (xiaoai) { + // 合并后音频文件存放目录 xx/botId/xiaoai/ String tmp_audio_name = StringUtils.join(new String[]{Initialize.getAudioDir(), botName, "xiaoai", TTSUtils.buildMP3Filename(file_ls.toString())}, File.separator); + // Double Check 加上锁 防止竞争情况 if (!TTSUtils.doesFileExist(tmp_audio_name)) { if (Boolean.TRUE.equals(stringRedisTemplate.opsForValue() .setIfAbsent(tmp_audio_name, "1", 20, TimeUnit.SECONDS))) { try { if (!TTSUtils.doesFileExist(tmp_audio_name)) { Files.createDirectories(Paths.get(tmp_audio_name).getParent()); + // 合并多个音频文件 TTSUtils.combineMp3File(file_ls, tmp_audio_name, true); if (!TTSUtils.doesFileExist(tmp_audio_name)) { log.error("小爱平台的请求,合并mp3文件失败:"+file_ls); @@ -1134,6 +1302,13 @@ public class TTServiceEdition2 { return true; } + /** + * + * @param response + * @param file_ls + * @param botName + * @param _type + */ private void dealHasB64FileRequest(HttpServletResponse response, List file_ls, String botName, String _type) { // 若请求字段_type为filename,则返回.b64文件的路径列表,负责返回所有.b64文件的内容数据