diff --git a/.idea/libraries/Maven__com_alibaba_fastjson_1_2_74.xml b/.idea/libraries/Maven__com_alibaba_fastjson_1_2_74.xml new file mode 100644 index 0000000..272f286 --- /dev/null +++ b/.idea/libraries/Maven__com_alibaba_fastjson_1_2_74.xml @@ -0,0 +1,13 @@ + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/workspace.xml b/.idea/workspace.xml index d3bb975..ce96822 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -7,19 +7,11 @@ - + - - - - - - - - @@ -59,10 +51,12 @@ - - + + + + @@ -72,32 +66,31 @@ - - + + + + - - + + - - - - - + + - - + + - - + + @@ -106,19 +99,10 @@ - + - - - - - - - - - - - + + @@ -135,19 +119,6 @@ - splitList - ttsRequest - buildMp - buildMP3Filename - successUpLoadFileIds - log - WELCOME_FORMAT - XIAO_AI_ENCRY_HOST - jiaoyouChannel2Bots - channelId - dealThirdParty - THIRD_PARTY_WITH_ITS_PER - tts_ls THIRD_PARTY_TTS commons httpcore @@ -165,6 +136,19 @@ respbody tencentProEnglishPerson speakerInfoRepository + createUtility + json + frame + os + okhttp + getOnline + xunfeiUseSSMLPerson + dealThirdParty + Path + return + sliceRequestThird + PERSON_INFO_ONLINE + name !CollectionUtils.isEmpty @@ -183,13 +167,6 @@ @@ -257,15 +241,6 @@ - - - - - - - - - + + @@ -394,8 +359,8 @@ - - + + @@ -543,13 +508,13 @@ + - @@ -785,15 +750,17 @@ - + + - - + + @@ -806,7 +773,7 @@ - + @@ -815,7 +782,7 @@ - + @@ -826,7 +793,7 @@ - + @@ -883,436 +850,427 @@ - + - - - - - + + - + - - + + + + + + - + - - + + - + - - + + - + - - + + - + - - + + - - + - - - - - - - - + - - + + - - + - + - - - - - - - - - - + + - + - - - - - + + - + - - - - - - - + + - + - - - - - + - + - - + + - - + - + - - + + - + - + - + - - + + - + - + - + - - + + + + + + + + + - + - - + + - - - - + - + - - + + - + - - + + - + - - + + + + + - + - - + + + + + - + - - + + - + - - + + - + - - - - - + + - + - - + + - + - - + + - + - - + + + + + - + - - + + + + + - + - - + + + + + - + - - + + - - + - + - - + + - + - - + + - + - - + + - + - - - - - + + - + - - - - - + + - + - - + + + + + + - + - - + + - + - - + + - + - - + + - + - - + + + + + + - + - - + + - + - - - - - + + - + - - + + - + + - + - - + + + + + + - + - - - - - + + - - + + + + - - - - - - - - - + + + + + + + + + + + - - + + diff --git a/tts_service/pom.xml b/tts_service/pom.xml index ef30c76..f324b2e 100755 --- a/tts_service/pom.xml +++ b/tts_service/pom.xml @@ -75,7 +75,7 @@ com.alibaba fastjson - 1.2.72 + 1.2.74 org.projectlombok diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java index 23df9e9..5f65536 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java @@ -37,7 +37,7 @@ public class OkHttp3Utils { /** * 客户端,超时时间设为10s */ - private static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder() + public static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .writeTimeout(10, TimeUnit.SECONDS) diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java index 3bb2e4f..d348094 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java @@ -52,6 +52,13 @@ public interface TTSConstants { String SECRET_KEY = "DqQkqcBWbU8oEPay96OSTEi1OVOegU0p"; } + interface XUN_FEI_TTS { + String HOST_URL = "https://tts-api.xfyun.cn/v2/tts"; + String APP_ID = "5f9f685d"; + String API_SECRET = "7e83135971a36c1124392ea495aabd4a"; + String API_KEY = "67596108f05733619d9866badb030234"; + } + interface Audio { String XIAOAI = "XIAOAI"; String XIAODU = "XIAODU"; diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiAudioRequest.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiAudioRequest.java new file mode 100644 index 0000000..d5a8a53 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiAudioRequest.java @@ -0,0 +1,18 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午11:11 + */ +@Getter +@Setter +@ToString +public class XunFeiAudioRequest { + private XunFeiRequestDataBusiness business = new XunFeiRequestDataBusiness(); + private XunFeiRequestDataCommon common = new XunFeiRequestDataCommon(); + private XunFeiRequestDataDatum data = new XunFeiRequestDataDatum(); +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiData.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiData.java new file mode 100644 index 0000000..ccb3971 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiData.java @@ -0,0 +1,20 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午10:50 + */ +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class XunFeiData { + private int status; //标志音频是否返回结束 status=1,表示后续还有音频返回,status=2表示所有的音频已经返回 + private String audio; //返回的音频,base64 编码 + private String ced; // 合成进度 +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataBusiness.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataBusiness.java new file mode 100644 index 0000000..cc1eb60 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataBusiness.java @@ -0,0 +1,24 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import com.fasterxml.jackson.annotation.JsonInclude; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午11:12 + */ +@Getter +@Setter +@ToString +@JsonInclude(JsonInclude.Include.NON_NULL) +public class XunFeiRequestDataBusiness { + private String aue = "raw"; + private Integer sfl; + private String tte = "UTF8";//小语种必须使用UNICODE编码 + private String vcn;//到控制台-我的应用-语音合成-添加试用或购买发音人,添加后即显示该发音人参数值,若试用未添加的发音人会报错11200 + private Integer speed = 50; + private Integer volume = 50; + private Integer pitch = 50; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataCommon.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataCommon.java new file mode 100644 index 0000000..cf7f177 --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataCommon.java @@ -0,0 +1,16 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午11:11 + */ +@Getter +@Setter +@ToString +public class XunFeiRequestDataCommon { + private String app_id; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataDatum.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataDatum.java new file mode 100644 index 0000000..cafa77f --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiRequestDataDatum.java @@ -0,0 +1,17 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午11:14 + */ +@Getter +@Setter +@ToString +public class XunFeiRequestDataDatum { + private String text; + private Integer status = 2; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiResponseData.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiResponseData.java new file mode 100644 index 0000000..c44c59e --- /dev/null +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/third/XunFeiResponseData.java @@ -0,0 +1,21 @@ +package ai.qiwu.com.tts_service.pojo.third; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + +/** + * painter + * 20-11-2 上午10:50 + */ +@Getter +@Setter +@ToString +@JsonIgnoreProperties(ignoreUnknown = true) +public class XunFeiResponseData { + private int code; + private String message; + private String sid; + private XunFeiData data; +} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java index 352400a..7826e1a 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Initialize.java @@ -150,6 +150,8 @@ public class Initialize implements InitializingBean { public static Set tencentProEnglishPerson; + public static Set xunfeiUseSSMLPerson; + // private static final int XIAODU_TEXT_SIZE_LIMIT; // private static final int LIEHU_TEXT_SIZE_LIMIT; @@ -161,6 +163,7 @@ public class Initialize implements InitializingBean { */ static { tencentProEnglishPerson = new HashSet<>(); + xunfeiUseSSMLPerson = new HashSet<>(); URL_LS = new ArrayList<>(); THIRD_PARTY_TTS = new HashSet<>(); ONLINE_ID_2_URL = new HashMap<>(); @@ -248,6 +251,13 @@ public class Initialize implements InitializingBean { THIRD_PARTY_WITH_ITS_PER.put("ProTencent29", "102002"); //贝紫 THIRD_PARTY_WITH_ITS_PER.put("ProTencent30", "102003"); //贝雪 + THIRD_PARTY_WITH_ITS_PER.put("XunFei1", "xiaoyan"); //讯飞小燕 + THIRD_PARTY_WITH_ITS_PER.put("XunFei2", "aisjiuxu"); //讯飞许久 + THIRD_PARTY_WITH_ITS_PER.put("XunFei3", "aisxping"); //讯飞小萍 + THIRD_PARTY_WITH_ITS_PER.put("XunFei4", "aisjinger"); //讯飞小婧 + THIRD_PARTY_WITH_ITS_PER.put("XunFei5", "aisbabyxu"); //讯飞许小宝 + + xunfeiUseSSMLPerson.add("XunFei1"); tencentProEnglishPerson.add("101050"); tencentProEnglishPerson.add("101051"); @@ -267,7 +277,7 @@ public class Initialize implements InitializingBean { * @param speakerInfo 记录信息 */ private void initialize(SpeakersInfo speakerInfo) { - String name = speakerInfo.getName(); + String name = StringUtils.startsWith(speakerInfo.getPerson(), "ProTencent") ? "腾"+speakerInfo.getName() : speakerInfo.getName(); String sex = speakerInfo.getSex(); String mood = speakerInfo.getMood(); Integer jump = speakerInfo.getJump(); 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 1eca577..c0be3d6 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 @@ -810,13 +810,113 @@ public class TTServiceEdition2 { private ResponseCodeWithData dealThirdParty(String text, String person, String filepath) { boolean result; // 去除所有{/../} - if (StringUtils.startsWith(person, "Baidu")) { - text = text.replaceAll("[\uD83C\uDD70\uD83C\uDD71]", "").trim(); - text = text.replace("{/", "("); - text = text.replace("/}", ")"); - } else { - text = text.replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "").trim(); +// text = text.replaceAll("[\uD83C\uDD70\uD83C\uDD71]", "").trim(); + if (text.contains("{/")) { + String prefix = person.substring(0, 5); + switch (prefix) { + case "Baidu" : { + text = text.replaceAll("\\{/", "("); + text = text.replaceAll("/}", ")"); + break; + } + case "XunFe" : { + if (Initialize.xunfeiUseSSMLPerson.contains(person)) { + StringBuilder temp = new StringBuilder(); + int sliceStart = 0; + for (int i = 0; i < text.length()-1; i++) { + if (text.charAt(i) == '{' && text.charAt(i+1) == '/') { + String mark = ""; + int markEnd = i+2; + char tempChar; + for (; markEnd < text.length(); markEnd++) { + if ((tempChar=text.charAt(markEnd)) == ' ') { + continue; + } else if (tempChar == '/') { + break; + } + mark += tempChar; + } + int j = i-1; + for (; j >= 0; j--) { + if (text.charAt(j) != ' ') { + break; + } + } + if (j == -1 && text.charAt(0) == ' ') { + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文本标音不正确"); + } + temp.append(text, sliceStart, j).append("").append(text.charAt(j)).append(""); + for (; markEnd < text.length(); markEnd++) { + if (text.charAt(markEnd) == '}') { + break; + } + } + sliceStart = markEnd+1; + } + } + if (sliceStart < text.length()) { + temp.append(text.substring(sliceStart)); + } + text = temp.toString(); + } else { + text = text.replaceAll("\\{/", "[="); + text = text.replaceAll("/}", "]"); + } + break; + } + case "ProTe" : { + StringBuilder temp = new StringBuilder(""); + int sliceStart = 0; + for (int i = 0; i < text.length()-1; i++) { + if (text.charAt(i) == '{' && text.charAt(i+1) == '/') { + String mark = ""; + int markEnd = i+2; + char tempChar; + for (; markEnd < text.length(); markEnd++) { + if ((tempChar=text.charAt(markEnd)) == ' ') { + continue; + } else if (tempChar == '/') { + break; + } + mark += tempChar; + } + int j = i-1; + for (; j >= 0; j--) { + if (text.charAt(j) != ' ') { + break; + } + } + if (j == -1 && text.charAt(0) == ' ') { + return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "文本标音不正确"); + } + temp.append(text, sliceStart, j).append("").append(text.charAt(j)).append(""); + for (; markEnd < text.length(); markEnd++) { + if (text.charAt(markEnd) == '}') { + break; + } + } + sliceStart = markEnd+1; + } + } + if (sliceStart < text.length()) { + temp.append(text.substring(sliceStart)); + } + + temp.append(""); + text = temp.toString(); + break; + } + default: { + text = text.replaceAll("\\{/.*?/}", "").trim(); + } + } } +// if (StringUtils.startsWith(person, "Baidu")) { +// text = text.replace("{/", "("); +// text = text.replace("/}", ")"); +// } else { +// text = text.replaceAll("\\{/.*?/}|\uD83C\uDD70|\uD83C\uDD71", "").trim(); +// } if (StringUtils.isBlank(text)) { log.error("第三方请求内容为空"); return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "第三方请求内容为空"); diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java index 15b1fbd..7edb8c8 100755 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java +++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java @@ -3,8 +3,7 @@ package ai.qiwu.com.tts_service.service.baidu; import ai.qiwu.com.tts_service.common.*; import ai.qiwu.com.tts_service.common.pcm.Pcm2Wav; import ai.qiwu.com.tts_service.common.TTSConstants.BAI_DU; -import ai.qiwu.com.tts_service.pojo.third.TecentTTSResponse; -import ai.qiwu.com.tts_service.pojo.third.TencentProTTSData; +import ai.qiwu.com.tts_service.pojo.third.*; import ai.qiwu.com.tts_service.service.Initialize; import ai.qiwu.com.tts_service.service.LieHuSchedule; import ai.qiwu.com.tts_service.service.TTService; @@ -18,18 +17,32 @@ import com.tencentcloudapi.common.profile.HttpProfile; import com.tencentcloudapi.tts.v20190823.TtsClient; import com.tencentcloudapi.tts.v20190823.models.TextToVoiceRequest; import lombok.extern.slf4j.Slf4j; +import okhttp3.*; +import okio.ByteString; import org.apache.commons.lang3.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; +import org.jetbrains.annotations.NotNull; import org.springframework.util.DigestUtils; +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; import java.io.*; +import java.net.URL; import java.net.URLEncoder; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.SimpleDateFormat; import java.time.Instant; import java.util.*; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** @@ -55,8 +68,10 @@ public class ThirdPartyService { clientProfile.setHttpProfile(httpProfile); TTS_CLIENT = new TtsClient(CREDENTIAL, "ap-guangzhou", clientProfile); + } + /** * 区分是百度的还是小雅的 * @param text 文本 @@ -69,21 +84,32 @@ public class ThirdPartyService { // person = getThirdPartyName(person); person = person.substring(0, 5); switch (person) { + // 文本小于2048个中文字或者英文数字 case "Baidu" : { return synthesis(text, Integer.parseInt(per), filepath); } + // 文本小于1500个中文字或者英文数字 case "Liehu" : { return lieHuTTS(text, per, filepath); } + // 合成语音的源文本,按UTF-8编码统一计算。 + //中文最大支持110个汉字(全角标点符号算一个汉字);英文最大支持350个字母(半角标点符号算一个字母)。 case "ProTe": { return tecentTTS(per, text, filepath); } + // 最大长度需小于8000字节,约2000汉字 + case "XunFe": { + try { + return xunFeiTTS(per, text, filepath); + } catch (Exception e) { + log.error("xunFeiTTS error:{}, text:{}, filepath:{}", e, text, filepath); + return false; + } + } + // 150 字节, 约35汉字 case "Tence" : { return tecentAITTS(per, text, filepath); } - case "TencentYOU" : { - return tecentYouTTS(per, text, filepath); - } default : { log.error("不支持该第三方平台:{}", person); return false; @@ -103,6 +129,171 @@ public class ThirdPartyService { // return false; } + // ============== XUN FEI =================== + + private static boolean xunFeiTTS(String per, String text, String filepath) throws Exception { + // 构建鉴权url +// String authUrl = getAuthUrl(); + //将url中的 schema http://和https://分别替换为ws:// 和 wss:// +// String url = getAuthUrl().replace("http://", "ws://").replace("https://", "wss://"); + Request request = new Request.Builder().url(getAuthUrl().replace("http://", "ws://") + .replace("https://", "wss://")).build(); + // 存放音频的文件 +// String pcmFilePath; +// FileOutputStream os = new FileOutputStream(new File((pcmFilePath=filepath.substring(0, filepath.lastIndexOf("."))+".pcm"))); + CountDownLatch latch = new CountDownLatch(1); + List audioBytesDataArr = new ArrayList<>(); + AtomicInteger allLn = new AtomicInteger(); + + WebSocket webSocket = OkHttp3Utils.ShortTimeoutClient.newWebSocket(request, new WebSocketListener() { + + @Override + public void onOpen(@NotNull WebSocket webSocket, @NotNull Response response) { + super.onOpen(webSocket, response); +// try { +// log.info(response.body().string()); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// log.info("start"); + //发送数据 + XunFeiAudioRequest audioRequest = new XunFeiAudioRequest(); + audioRequest.getCommon().setApp_id(TTSConstants.XUN_FEI_TTS.APP_ID); + + //填充business + XunFeiRequestDataBusiness business = audioRequest.getBusiness(); + business.setVcn(per); + + //填充data + audioRequest.getData().setText(Base64.getEncoder().encodeToString(text.getBytes(StandardCharsets.UTF_8))); + //使用小语种须使用下面的代码,此处的unicode指的是 utf16小端的编码方式,即"UTF-16LE"” + //data.addProperty("text", Base64.getEncoder().encodeToString(text.getBytes("UTF-16LE"))); + webSocket.send(JSON.toJSONString(audioRequest)); + } + + @Override + public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) { + super.onMessage(webSocket, text); + //处理返回数据 +// System.out.println("receive=>" + text); +// log.info("receive"); + XunFeiResponseData resp = JSON.parseObject(text, XunFeiResponseData.class); + if (resp != null) { + if (resp.getCode() != 0) { + log.error("xunfei websocket code:{},errorMsg:{}, sid:{}",resp.getCode(), resp.getMessage(), resp.getSid()); +// webSocket.close(1000, ""); +// try { +// out.close(); +// } catch (IOException e) { +// log.error(ExceptionUtils.getStackTrace(e)); +// } +// latch.countDown(); + return; + } + if (resp.getData() != null) { +// byte[] data = Base64.getDecoder().decode(resp.getData().getAudio()); +// try (AudioInputStream audioInputStream = new AudioInputStream(new ByteArrayInputStream(data), audioFormat, data.length)){ +// AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out); +// out.flush(); +// } catch (IOException e) { +// log.error("xunfei pcm转换成wav出错:{}", e.toString()); +// return; +// } + byte[] sliceArr; + audioBytesDataArr.add((sliceArr=Base64.getDecoder().decode(resp.getData().getAudio()))); + allLn.addAndGet(sliceArr.length); +// try { +// os.write(Base64.getDecoder().decode(resp.getData().getAudio())); +// os.flush(); +// } catch (IOException e) { +// log.error(ExceptionUtils.getStackTrace(e)); +// } + if (resp.getData().getStatus() == 2) { + // todo resp.data.status ==2 说明数据全部返回完毕,可以关闭连接,释放资源 +// System.out.println("session end "); +// System.out.println("合成的音频文件保存在:" + f.getPath()); + try { + ByteBuffer buffer = ByteBuffer.allocate(allLn.get()); + audioBytesDataArr.forEach(buffer::put); + Pcm2Wav.pcm2Wav(buffer.array(), filepath); + }catch (Exception e) { + log.error("pcm change to wav fail:"+e); + } + webSocket.close(1000, ""); +// try { +// out.close(); +// } catch (IOException e) { +// log.error(ExceptionUtils.getStackTrace(e)); +// } +// CallPython.ffmpegExecute("ffmpeg -f s16le -ar 16000 -ac 1 -i "+pcmFilePath+" "+filepath); +// TTService.POOL.submit(() -> Files.deleteIfExists(Paths.get(pcmFilePath))); + latch.countDown(); + } + } + } + } + @Override + public void onMessage(@NotNull WebSocket webSocket, @NotNull ByteString bytes) { + super.onMessage(webSocket, bytes); + } + @Override + public void onClosing(@NotNull WebSocket webSocket, int code, @NotNull String reason) { + super.onClosing(webSocket, code, reason); +// log.info("XUN FEI socket closing"); + } + @Override + public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) { + super.onClosed(webSocket, code, reason); +// log.info("XUN FEI socket closed"); + } + @Override + public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, Response response) { + super.onFailure(webSocket, t, response); + log.error("XUN FEI connection failed:{}", t.getMessage()); + webSocket.close(1000, "onFailure"); + latch.countDown(); + } + }); + if (latch.await(30, TimeUnit.SECONDS)) { + Path pt; + if (Files.exists((pt=Paths.get(filepath)))) { + if (Files.size(pt) == 0) { + Files.deleteIfExists(pt); + return false; + } + return true; + } + return false; + } + log.error("xunFeiTTS time out 30s,text:{}, filepath:{}", text, filepath); + webSocket.close(1000, "TIME OUT 30s"); + return false; + } + + private static String getAuthUrl() throws Exception { + URL url = new URL(TTSConstants.XUN_FEI_TTS.HOST_URL); + SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); + format.setTimeZone(TimeZone.getTimeZone("GMT")); + String date = format.format(new Date()); + StringBuilder builder = new StringBuilder("host: ").append(url.getHost()).append("\n").// + append("date: ").append(date).append("\n").// + append("GET ").append(url.getPath()).append(" HTTP/1.1"); + Charset charset = Charset.forName("UTF-8"); + Mac mac = Mac.getInstance("hmacsha256"); + SecretKeySpec spec = new SecretKeySpec(TTSConstants.XUN_FEI_TTS.API_SECRET.getBytes(charset), "hmacsha256"); + mac.init(spec); + byte[] hexDigits = mac.doFinal(builder.toString().getBytes(charset)); + String sha = Base64.getEncoder().encodeToString(hexDigits); + String authorization = String.format("hmac username=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", TTSConstants.XUN_FEI_TTS.API_KEY, "hmac-sha256", "host date request-line", sha); + HttpUrl httpUrl = HttpUrl.parse("https://" + url.getHost() + url.getPath()).newBuilder().// + addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(charset))).// + addQueryParameter("date", date).// + addQueryParameter("host", url.getHost()).// + build(); + return httpUrl.toString(); + } + + // ============== TENCENT =================== private static boolean tecentTTS(String per, String text, String filepath) { try{ TextToVoiceRequest req = new TextToVoiceRequest(); @@ -218,6 +409,52 @@ public class ThirdPartyService { return false; } + // ===================== slice text ========================== + + private static void sliceTextRecur(String text, int bound, List slices, String mark) { + String[] arr = text.split(mark); + if (arr.length == 1 || (arr.length == 2 && StringUtils.isAnyBlank(arr[0], arr[1]))) { + + } + } + + private static void sliceText(String text, int bound) { + List slices = new ArrayList<>(); + // ??。;.!! + String[] arr = text.split("[。.]"); + String slice = ""; + for (String txt: arr) { + txt = txt.trim(); + if (txt.length() == 0) { + continue; + } else if (txt.length() >= bound) { + if (slice.length() > 0) { + slices.add(slice); + slice = ""; + } + String[] arr2 = txt.split("[??]"); + if (arr2.length == 1 || (arr2.length == 2 && StringUtils.isAnyBlank(arr2[0], arr2[1]))) { + arr2 = txt.split("[!!]"); + if (arr2.length == 1 || (arr2.length == 2 && StringUtils.isAnyBlank(arr2[0], arr2[1]))) { + arr2 = txt.split("[;]"); + if (arr2.length == 1 || (arr2.length == 2 && StringUtils.isAnyBlank(arr2[0], arr2[1]))) { + arr2 = txt.split("[,,]"); + if (arr2.length == 1 || (arr2.length == 2 && StringUtils.isAnyBlank(arr2[0], arr2[1]))) { + + } + } + } + } + + } + if (slice.length() > bound) { + + } else { + slices.add(txt); + } + } + } + private static void sliceRequestThird(ArrayDeque deque, int per, String filepath) { List> results = new ArrayList<>(); String pre = filepath.substring(0, filepath.lastIndexOf(".")); @@ -352,9 +589,10 @@ public class ThirdPartyService { } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { // synthesis("佳人微醺,现在的她充满活力,要夸夸她吗?", 106, "/home/yf01/testttt.wav");\ // System.out.println(tecentYouTTS("2", "今天是个好天气", "/home/yf01/下载/audioCut/tecentYou01.wav")); // System.out.println(tecentTTS("5", "今天天气", "/home/yf01/下载/audioCut/tecentPro01.wav")); + xunFeiTTS("xiaoyan", "今天是个好天气。佳人微醺,现在的她充满活力,要夸夸她吗", "/home/yf01/下载/audioCut/tecentXunFei06.wav"); } }