diff --git a/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_common_2_1_9.xml b/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_common_2_1_9.xml
new file mode 100644
index 0000000..1a2e92f
--- /dev/null
+++ b/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_common_2_1_9.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_tts_2_1_9.xml b/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_tts_2_1_9.xml
new file mode 100644
index 0000000..e9ee7b0
--- /dev/null
+++ b/.idea/libraries/Maven__com_alibaba_nls_nls_sdk_tts_2_1_9.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/libraries/Maven__io_netty_netty_codec_http_4_1_49_Final.xml b/.idea/libraries/Maven__io_netty_netty_codec_http_4_1_49_Final.xml
new file mode 100644
index 0000000..2dbd8c5
--- /dev/null
+++ b/.idea/libraries/Maven__io_netty_netty_codec_http_4_1_49_Final.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index ce96822..58a9732 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -7,9 +7,11 @@
-
-
+
+
+
+
@@ -51,8 +53,8 @@
-
-
+
+
@@ -66,22 +68,29 @@
-
-
+
+
-
-
+
+
+
+
+
+
+
+
+
-
-
+
+
@@ -89,10 +98,11 @@
-
-
+
+
+
@@ -101,8 +111,8 @@
-
-
+
+
@@ -119,19 +129,6 @@
- THIRD_PARTY_TTS
- commons
- httpcore
- TtsSynSender
- customizedParams
- strResp
- TextToVoiceResponse
- jsonPayload
- requestPayload
- url
- TTS_CLIENT
- hashedRequestPayload
- request
TextToVoiceRequest
respbody
tencentProEnglishPerson
@@ -146,9 +143,22 @@
dealThirdParty
Path
return
+ name
sliceRequestThird
PERSON_INFO_ONLINE
- name
+ cutedPaths
+ substring
+ tecentAITTS
+ 44
+ text
+ keySet
+ slices
+ slice.length
+ markCount
+ TTS_CLIENT
+ nld
+ nls
+ token
!CollectionUtils.isEmpty
@@ -167,8 +177,6 @@
@@ -249,8 +259,8 @@
-
-
+
+
@@ -347,8 +357,8 @@
-
+
@@ -359,7 +369,7 @@
-
+
@@ -395,13 +405,13 @@
-
-
-
-
+
+
+
+
-
+
@@ -505,7 +515,6 @@
-
@@ -515,14 +524,15 @@
+
+
-
@@ -751,15 +761,16 @@
-
+
+
-
+
-
+
@@ -773,7 +784,7 @@
-
+
@@ -781,7 +792,7 @@
-
+
@@ -850,93 +861,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -988,30 +912,8 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
@@ -1039,20 +941,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -1149,17 +1037,6 @@
-
-
-
-
-
-
-
-
-
-
-
@@ -1174,13 +1051,6 @@
-
-
-
-
-
-
-
@@ -1228,17 +1098,21 @@
-
+
-
-
+
+
+
+
+
+
-
-
+
+
@@ -1248,31 +1122,162 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
+
+
+
+
+
-
-
+
+
+
diff --git a/tts_service/pom.xml b/tts_service/pom.xml
index f324b2e..cd91630 100755
--- a/tts_service/pom.xml
+++ b/tts_service/pom.xml
@@ -134,6 +134,12 @@
commons-csv
1.7
+
+
+ com.alibaba.nls
+ nls-sdk-tts
+ 2.1.9
+
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 d348094..8f1ac9b 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
@@ -47,9 +47,9 @@ public interface TTSConstants {
}
interface TENCENT_PROFESSION_TTS_ID {
- String APP_ID = "1304075838";
- String SECRET_ID = "AKIDjfMnytjxiFXa9UEs61hcIn4Zs0tc5ui0";
- String SECRET_KEY = "DqQkqcBWbU8oEPay96OSTEi1OVOegU0p";
+// String APP_ID = "1259060820";
+ String SECRET_ID = "AKID60nOmwBqTr3JmzweR2MS9TaS6zh9pEyV";
+ String SECRET_KEY = "ReptlPxIRHuPkrmZ9VvondRNTnxtpX6R";
}
interface XUN_FEI_TTS {
@@ -59,6 +59,11 @@ public interface TTSConstants {
String API_KEY = "67596108f05733619d9866badb030234";
}
+ interface ALI_TTS {
+ String ACCESS_KEY_ID = "";
+ String ACCESS_KEY_SECRET = "";
+ }
+
interface Audio {
String XIAOAI = "XIAOAI";
String XIAODU = "XIAODU";
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 b0d33b1..e32c3bc 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
@@ -694,6 +694,68 @@ public class TTSUtils {
});
}
+ public static void thirdSoxCutAndCombineWav(Collection filePathList, String targetFilepath) {
+ int i = 0, ln = filePathList.size()-1;
+ String tempPath;
+ List resultList = new ArrayList<>(ln+1);
+ List cutedPaths = new ArrayList<>(resultList.size());
+ for (String sourcePath: filePathList) {
+ StringBuilder soxCutCommand = new StringBuilder("sox ");
+ if (i == 0) {
+ tempPath = sourcePath.substring(0, sourcePath.lastIndexOf("."))+"_l.wav";
+ soxCutCommand.append(sourcePath).append(" ").append(tempPath).append(" reverse silence 1 0.1 1% reverse");
+ }else if (i == ln) {
+ tempPath = sourcePath.substring(0, sourcePath.lastIndexOf("."))+"_f.wav";
+ soxCutCommand.append(sourcePath).append(" ").append(tempPath).append(" silence 1 0.1 1%");
+ } else {
+ tempPath = sourcePath.substring(0, sourcePath.lastIndexOf("."))+"_a.wav";
+ soxCutCommand.append(sourcePath).append(" ").append(tempPath).append(" silence 1 0.1 1% reverse silence 1 0.1 1% reverse");
+ }
+ i++;
+ if (!cutedPaths.contains(tempPath)) {
+ if (!doesFileExist(tempPath)) {
+ resultList.add(POOL.submit(() -> {
+ CallPython.soxCut(soxCutCommand.toString());
+ }));
+ }
+ }
+ cutedPaths.add(tempPath);
+ }
+ for (Future future: resultList) {
+ try {
+ future.get(10, TimeUnit.SECONDS);
+ } catch (InterruptedException | ExecutionException e) {
+ log.error("soxCutAndCombineWav ,分段任务执行出错:"+e);
+ } catch (TimeoutException e2) {
+ log.error("soxCutAndCombineWav ,等待10s分段任务仍未执行结束");
+ }
+ }
+// long temp;
+// log.warn("sox 切除静音耗时:"+((temp=System.currentTimeMillis())-startMark));
+ List str = cutedPaths.stream().map(s -> {
+ if (Files.exists(Paths.get(s))) {
+ return "-i " + s;
+ } else {
+ return "-i " + s.substring(0, s.lastIndexOf("_"))+".wav";
+ }
+ }).collect(Collectors.toList());
+ StringBuilder builder = new StringBuilder("ffmpeg ").append(StringUtils.join(str, " ")).append(" -filter_complex ");
+ for (int k = 0; k < filePathList.size(); k++) {
+ builder.append("[").append(k).append(":a:0]");
+ }
+ builder.append("concat=n=").append(filePathList.size()).append(":v=0:a=1[a] -map [a] -b:a 64k -y ").append(targetFilepath);
+ CallPython.ffmpegExecute(builder.toString());
+// log.warn("ffmpeg 拼接耗时:"+(System.currentTimeMillis()-temp));
+ POOL.submit(() -> {
+ cutedPaths.addAll(filePathList);
+ for (String delPath: cutedPaths) {
+ try {
+ Files.deleteIfExists(Paths.get(delPath));
+ } catch (Exception e) {}
+ }
+ });
+ }
+
/**
* 节点
* @param
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/Pcm2Wav.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/Pcm2Wav.java
index 274d950..245f76c 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/Pcm2Wav.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/Pcm2Wav.java
@@ -8,6 +8,10 @@ import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import java.io.*;
+import java.text.SimpleDateFormat;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.util.Date;
/**
* pcm转换为wav
@@ -40,5 +44,13 @@ public class Pcm2Wav {
}
public static void main(String[] args) {
// ThirdPartyService.lieHuTTS("绿洲有美丽的风景,好吃的食物,湛蓝的天空,蔚蓝的海洋", "1", "/home/yf01/testPcm.wav");
+// System.out.println("着手办理此事".length());
+// String text;
+// System.out.println((text="绿洲有美丽的风景,好吃的食物,湛蓝的天空,蔚蓝的海洋,着手办理此事,这是人行横道").length());
+// text = text.substring(7, text.length()-8);
+// System.out.println(ThirdPartyService.proTencentTextSlice(text, 6));
+
+ String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) * 1000L));
+ System.out.println("Token有效期的北京时间:" + expireDate);
}
}
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 981ba58..3714a59 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
@@ -67,8 +67,8 @@ public class TTSController {
// private final CdnService cdnService;
- @Autowired
- private StringRedisTemplate stringRedisTemplate;
+// @Autowired
+// private StringRedisTemplate stringRedisTemplate;
@Autowired
public TTSController(TTService ttService, TTServiceEdition2 ttServiceEdition2, LieHuSchedule lieHuSchedule) {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/LieHuSchedule.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/LieHuSchedule.java
index 392de9b..60eeaa4 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/LieHuSchedule.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/LieHuSchedule.java
@@ -4,11 +4,18 @@ import ai.qiwu.com.tts_service.common.OkHttp3Utils;
import ai.qiwu.com.tts_service.common.TTSConstants;
import ai.qiwu.com.tts_service.pojo.third.LieHuTokenResponse;
import com.alibaba.fastjson.JSON;
+import com.alibaba.nls.client.AccessToken;
+import com.alibaba.nls.client.protocol.NlsClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
+import java.io.IOException;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
import java.util.HashMap;
/**
@@ -24,6 +31,9 @@ public class LieHuSchedule {
// private static final HashMap LIE_HU_TOKEN_HEADER;
private static String LIE_HU_TOKEN;
+ public static NlsClient nlsClient;
+ private static volatile AccessToken accessToken;
+
static {
LIE_HU_TOKEN_PARAMS = new HashMap<>();
// LIE_HU_TOKEN_HEADER = new HashMap<>();
@@ -35,6 +45,41 @@ public class LieHuSchedule {
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
+ @Scheduled(fixedDelay = 1800000)
+ public void scheduleALiTTSToken() {
+ if (accessToken == null) {
+ accessToken = new AccessToken(TTSConstants.ALI_TTS.ACCESS_KEY_ID, TTSConstants.ALI_TTS.ACCESS_KEY_SECRET);
+ try {
+ accessToken.apply();
+ log.warn("阿里TTS token 超时时间:"+accessToken.getExpireTime());
+ nlsClient = new NlsClient(accessToken.getToken());
+ } catch (IOException e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ }
+ } else {
+ if (accessToken.getExpireTime() - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) <= 300) {
+ boolean refreshTokenSuccess = false;
+ int refreshCount = 0;
+ do {
+ refreshCount++;
+ try {
+ accessToken.apply();
+ nlsClient.setToken(accessToken.getToken());
+ refreshTokenSuccess = true;
+ log.warn("刷新阿里TTS token, 超时时间:"+accessToken.getExpireTime());
+ } catch (IOException e) {
+ log.error("第:{}次刷新阿里TTS TOKEN 失败:{}", refreshCount, e);
+ try {
+ Thread.sleep(refreshCount*5000);
+ } catch (InterruptedException e1) {
+ // do nothing
+ }
+ }
+ } while (!refreshTokenSuccess && refreshCount <= 5);
+ }
+ }
+ }
+
@Scheduled(fixedDelay = 6600000)
public void scheduleLieHuToken() {
new Thread(() -> {
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 c0be3d6..b20fd1e 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
@@ -889,7 +889,7 @@ public class TTServiceEdition2 {
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("");
+ temp.append(text, sliceStart, j).append("").append(text.charAt(j)).append("");
for (; markEnd < text.length(); markEnd++) {
if (text.charAt(markEnd) == '}') {
break;
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 7edb8c8..8e31b5d 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
@@ -8,6 +8,11 @@ import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.LieHuSchedule;
import ai.qiwu.com.tts_service.service.TTService;
import com.alibaba.fastjson.JSON;
+import com.alibaba.nls.client.protocol.OutputFormatEnum;
+import com.alibaba.nls.client.protocol.SampleRateEnum;
+import com.alibaba.nls.client.protocol.tts.SpeechSynthesizer;
+import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
+import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.baidu.aip.speech.AipSpeech;
import com.baidu.aip.speech.TtsResponse;
import com.tencentcloudapi.aai.v20180522.models.TextToVoiceResponse;
@@ -21,6 +26,7 @@ import okhttp3.*;
import okio.ByteString;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.DigestUtils;
@@ -41,6 +47,7 @@ import java.time.Instant;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
+import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
@@ -59,6 +66,7 @@ public class ThirdPartyService {
private static final TtsClient TTS_CLIENT;
+ private static final Semaphore TENCENT_AI_TTS_LOCK;
static {
Credential CREDENTIAL = new Credential(TTSConstants.TENCENT_PROFESSION_TTS_ID.SECRET_ID, TTSConstants.TENCENT_PROFESSION_TTS_ID.SECRET_KEY);
HttpProfile httpProfile = new HttpProfile();
@@ -68,7 +76,7 @@ public class ThirdPartyService {
clientProfile.setHttpProfile(httpProfile);
TTS_CLIENT = new TtsClient(CREDENTIAL, "ap-guangzhou", clientProfile);
-
+ TENCENT_AI_TTS_LOCK = new Semaphore(2);
}
@@ -95,6 +103,53 @@ public class ThirdPartyService {
// 合成语音的源文本,按UTF-8编码统一计算。
//中文最大支持110个汉字(全角标点符号算一个汉字);英文最大支持350个字母(半角标点符号算一个字母)。
case "ProTe": {
+ if (StringUtils.startsWith(text, "")) {
+ int index = 0, markCount = 0;
+ while (index < text.length() && (index = text.indexOf("", index)) != -1) {
+ index += 10;
+ markCount++;
+ }
+ if (text.length() > 120+44*markCount) {
+ text = text.substring(7, text.length()-8);
+ List slices = proTencentTextSlice(text, 105);
+ List tempPtList = new ArrayList<>();
+ String tempPt;
+ for (int i = 0; i < slices.size(); i++) {
+ tempPt = filepath.lastIndexOf(".")+"_"+i+".wav";
+ tempPtList.add(tempPt);
+ if (!tecentTTS(per, slices.get(i), tempPt)) {
+ TTService.POOL.submit(() -> tempPtList.forEach(s -> {
+ try {
+ Files.deleteIfExists(Paths.get(s));
+ } catch (Exception e) {}
+ }));
+ return false;
+ }
+ }
+ TTSUtils.thirdSoxCutAndCombineWav(tempPtList, filepath);
+ return true;
+ }
+ } else {
+ if (text.length() > 105) {
+ List slices = sliceText(text, 105);
+ List tempPtList = new ArrayList<>();
+ String tempPt;
+ for (int i = 0; i < slices.size(); i++) {
+ tempPt = filepath.lastIndexOf(".")+"_"+i+".wav";
+ tempPtList.add(tempPt);
+ if (!tecentTTS(per, slices.get(i), tempPt)) {
+ TTService.POOL.submit(() -> tempPtList.forEach(s -> {
+ try {
+ Files.deleteIfExists(Paths.get(s));
+ } catch (Exception e) {}
+ }));
+ return false;
+ }
+ }
+ TTSUtils.thirdSoxCutAndCombineWav(tempPtList, filepath);
+ return true;
+ }
+ }
return tecentTTS(per, text, filepath);
}
// 最大长度需小于8000字节,约2000汉字
@@ -106,8 +161,27 @@ public class ThirdPartyService {
return false;
}
}
- // 150 字节, 约35汉字
+ // 150 字节, 测试上限约50汉字
case "Tence" : {
+ if (text.length() > 45) {
+ List slices = sliceText(text, 45);
+ List tempPtList = new ArrayList<>();
+ String tempPt;
+ for (int i = 0; i < slices.size(); i++) {
+ tempPt = filepath.lastIndexOf(".")+"_"+i+".wav";
+ tempPtList.add(tempPt);
+ if (!tecentAITTS(per, slices.get(i), tempPt)) {
+ TTService.POOL.submit(() -> tempPtList.forEach(s -> {
+ try {
+ Files.deleteIfExists(Paths.get(s));
+ } catch (Exception e) {}
+ }));
+ return false;
+ }
+ }
+ TTSUtils.thirdSoxCutAndCombineWav(tempPtList, filepath);
+ return true;
+ }
return tecentAITTS(per, text, filepath);
}
default : {
@@ -129,6 +203,91 @@ public class ThirdPartyService {
// return false;
}
+ // ============== ALI =======================
+ private static boolean aliTTS(String per, String text, String filepath) {
+ SpeechSynthesizer synthesizer = null;
+ try {
+ //创建实例,建立连接。
+ synthesizer = new SpeechSynthesizer(LieHuSchedule.nlsClient, getSynthesizerListener());
+ synthesizer.setAppKey(TTSConstants.ALI_TTS.ACCESS_KEY_ID);
+ //设置返回音频的编码格式
+ synthesizer.setFormat(OutputFormatEnum.WAV);
+ //设置返回音频的采样率
+ synthesizer.setSampleRate(SampleRateEnum.SAMPLE_RATE_16K);
+ //发音人
+ synthesizer.setVoice(per);
+ //语调,范围是-500~500,可选,默认是0。
+ synthesizer.setPitchRate(0);
+ //语速,范围是-500~500,默认是0。
+ synthesizer.setSpeechRate(0);
+ //设置用于语音合成的文本
+ synthesizer.setText(text);
+ // 是否开启字幕功能(返回相应文本的时间戳),默认不开启,需要注意并非所有发音人都支持该参数。
+ synthesizer.addCustomedParam("enable_subtitle", false);
+ //此方法将以上参数设置序列化为JSON格式发送给服务端,并等待服务端确认。
+ long start = System.currentTimeMillis();
+ synthesizer.start();
+ log.info("tts start latency " + (System.currentTimeMillis() - start) + " ms");
+ //等待语音合成结束
+ synthesizer.waitForComplete();
+ log.info("tts stop latency " + (System.currentTimeMillis() - start) + " ms");
+ } catch (Exception e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ } finally {
+ //关闭连接
+ if (null != synthesizer) {
+ synthesizer.close();
+ }
+ }
+ }
+
+ private static SpeechSynthesizerListener getSynthesizerListener(String filePath) {
+ SpeechSynthesizerListener listener = null;
+ try {
+ listener = new SpeechSynthesizerListener() {
+ FileOutputStream fout = new FileOutputStream(new File(filePath));
+ private boolean firstRecvBinary = true;
+ //语音合成结束
+ @Override
+ public void onComplete(SpeechSynthesizerResponse response) {
+ //调用onComplete时表示所有TTS数据已接收完成,因此为整个合成数据的延迟。该延迟可能较大,不一定满足实时场景。
+ try {
+ fout.close();
+ } catch (Exception e){}
+ log.info("name:{}, status:{}, path:{}",response.getName(), response.getStatus(), filePath);
+ }
+ //语音合成的语音二进制数据
+ @Override
+ public void onMessage(ByteBuffer message) {
+ try {
+ if(firstRecvBinary) {
+ //计算首包语音流的延迟,收到第一包语音流时,即可以进行语音播放,以提升响应速度(特别是实时交互场景下)。
+ firstRecvBinary = false;
+ log.info("tts first latency");
+ }
+ byte[] bytesArray = new byte[message.remaining()];
+ message.get(bytesArray, 0, bytesArray.length);
+ fout.write(bytesArray);
+ } catch (IOException e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ }
+ }
+ @Override
+ public void onFail(SpeechSynthesizerResponse response){
+ //task_id是调用方和服务端通信的唯一标识,当遇到问题时需要提供task_id以便排查。
+ //状态码 20000000 表示识别成功
+ try {
+ fout.close();
+ } catch (Exception e){}
+ log.error("阿里TTS下载失败,task_id:{}, status:{}, status_text:{}", response.getTaskId(), response.getStatus(), response.getStatusText());
+ }
+ };
+ } catch (Exception e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ }
+ return listener;
+ }
+
// ============== XUN FEI ===================
private static boolean xunFeiTTS(String per, String text, String filepath) throws Exception {
@@ -311,48 +470,63 @@ public class ThirdPartyService {
log.error("写入腾讯tts wav数据信息失败:{}, text:{}, res:{}", e, text, res);
}
} catch (Exception e) {
- System.out.println(e.toString());
+ log.error(ExceptionUtils.getStackTrace(e));
}
return false;
}
private static boolean tecentAITTS(String per, String text, String filepath) {
- TreeMap params = new TreeMap<>();
- params.put("app_id", TTSConstants.TENCENT_AUDIO_ID.APP_ID);
- long secondStamp;
- params.put("time_stamp", String.valueOf((secondStamp=Instant.now().getEpochSecond())));
- params.put("nonce_str", secondStamp+RandomStringUtils.random(7, true, true));
- params.put("speaker", per);
- params.put("format", "2");
- params.put("volume", "0");
- params.put("speed", "100");
- params.put("aht", "0");
- params.put("apc", "58");
- params.put("text", text);
- String sign = params.entrySet().stream().map(entry -> {
- try {
- return entry.getKey()+"="+ URLEncoder.encode(entry.getValue(), "UTF-8");
- } catch (Exception e) {
- return null;
+ boolean acquireSuccess = false;
+ try {
+ acquireSuccess = TENCENT_AI_TTS_LOCK.tryAcquire(15, TimeUnit.SECONDS);
+ if (!acquireSuccess) {
+ log.warn("tecentAITTS 等待锁超时:text:{}, filepath:{}", text, filepath);
+ return false;
}
- }).collect(Collectors.joining("&"));
- sign += TTSConstants.TENCENT_AUDIO_ID.App_Key_WITH_PREFIX;
- params.put("sign", StringUtils.upperCase(DigestUtils.md5DigestAsHex(sign.getBytes(StandardCharsets.UTF_8))));
- String result = ApachHttpUtils.get("https://api.ai.qq.com/fcgi-bin/aai/aai_tts", null, params);
- if (StringUtils.isBlank(result)) {
- log.error("请求腾讯AI tts出错,结果为空:"+text);
- } else {
- TecentTTSResponse response = JSON.parseObject(result, TecentTTSResponse.class);
- if (NumberUtils.INTEGER_ZERO.equals(response.getRet())) {
- try (FileOutputStream output = new FileOutputStream(new File(filepath))){
- output.write(Base64.getDecoder().decode(response.getData().getSpeech().getBytes(StandardCharsets.UTF_8)));
- return true;
+ TreeMap params = new TreeMap<>();
+ params.put("app_id", TTSConstants.TENCENT_AUDIO_ID.APP_ID);
+ long secondStamp;
+ params.put("time_stamp", String.valueOf((secondStamp=Instant.now().getEpochSecond())));
+ params.put("nonce_str", secondStamp+RandomStringUtils.random(7, true, true));
+ params.put("speaker", per);
+ params.put("format", "2");
+ params.put("volume", "0");
+ params.put("speed", "100");
+ params.put("aht", "0");
+ params.put("apc", "58");
+ params.put("text", text);
+ String sign = params.entrySet().stream().map(entry -> {
+ try {
+ return entry.getKey()+"="+ URLEncoder.encode(entry.getValue(), "UTF-8");
} catch (Exception e) {
- log.error("写入腾讯AI tts wav数据信息失败:{}, text:{}", e, text);
+ return null;
}
+ }).collect(Collectors.joining("&"));
+ sign += TTSConstants.TENCENT_AUDIO_ID.App_Key_WITH_PREFIX;
+ params.put("sign", StringUtils.upperCase(DigestUtils.md5DigestAsHex(sign.getBytes(StandardCharsets.UTF_8))));
+ String result = ApachHttpUtils.get("https://api.ai.qq.com/fcgi-bin/aai/aai_tts", null, params);
+ if (StringUtils.isBlank(result)) {
+ log.error("请求腾讯AI tts出错,结果为空:"+text);
} else {
- // https://ai.qq.com/doc/returncode.shtml
- log.error("请求腾讯AI tts 不成功:"+result);
+ TecentTTSResponse response = JSON.parseObject(result, TecentTTSResponse.class);
+ if (NumberUtils.INTEGER_ZERO.equals(response.getRet())) {
+ try (FileOutputStream output = new FileOutputStream(new File(filepath))){
+ output.write(Base64.getDecoder().decode(response.getData().getSpeech().getBytes(StandardCharsets.UTF_8)));
+ return true;
+ } catch (Exception e) {
+ log.error("写入腾讯AI tts wav数据信息失败:{}, text:{}", e, text);
+ }
+ } else {
+ // https://ai.qq.com/doc/returncode.shtml
+ log.error("请求腾讯AI tts 不成功:{}, text:{}",result,text);
+ }
+ }
+ return false;
+ } catch (InterruptedException e) {
+ log.error(ExceptionUtils.getStackTrace(e));
+ } finally {
+ if (acquireSuccess) {
+ TENCENT_AI_TTS_LOCK.release();
}
}
return false;
@@ -411,48 +585,232 @@ public class ThirdPartyService {
// ===================== 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]))) {
-
+ public static List proTencentTextSlice(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;
+ }
+ int index = 0, markCount = 0;
+ while (index < txt.length() && (index = txt.indexOf("", index)) != -1) {
+ index += 10;
+ markCount++;
+ }
+ boolean biaoinMarkExist = markCount != 0;
+ if (txt.length() > bound+markCount*44) {
+ if (slice.length() > 0) {
+ if (slice.contains(""+slice+"");
+ } else {
+ slices.add(slice);
+ }
+ slice = "";
+ }
+ String[] commaSlice = txt.split("[,,]");
+ if (commaSlice.length == 1 || (commaSlice.length == 2 && StringUtils.isAnyBlank(commaSlice[0], commaSlice[1]))) {
+ dealTencentLongText(biaoinMarkExist, txt, bound, slices);
+ } else {
+ for (String comma: commaSlice) {
+ if (StringUtils.isBlank(comma)) {
+ continue;
+ }
+ int ci = 0, cc = 0;
+ while (ci < comma.length() && (ci = comma.indexOf("", ci)) != -1) {
+ ci += 10;
+ cc++;
+ }
+ boolean biaoyinExist = cc != 0;
+ if (comma.length() > bound+cc*44) {
+ if (slice.length() > 0) {
+ if (slice.contains(""+slice+"");
+ } else {
+ slices.add(slice);
+ }
+ slice = "";
+ }
+ dealTencentLongText(biaoyinExist, comma, bound, slices);
+ } else {
+ if (slice.length() == 0) {
+ slice = comma;
+ } else {
+ int si = 0, sc = 0;
+ while (si < slice.length() && (si = slice.indexOf("", si)) != -1) {
+ si += 10;
+ sc++;
+ }
+ if (slice.length()+comma.length() >= bound+(cc+sc)*44) {
+ if (sc == 0) {
+ slices.add(slice);
+ } else {
+ slices.add(""+slice+"");
+ }
+ slice = comma;
+ } else {
+ slice += "," + comma;
+ }
+ }
+ }
+ }
+ }
+ } else {
+ if (slice.length() == 0) {
+ slice = txt;
+ } else {
+ int si = 0, sc = 0;
+ while (si < slice.length() && (si = slice.indexOf("", si)) != -1) {
+ si += 10;
+ sc++;
+ }
+ if (slice.length()+txt.length() >= bound+(markCount+sc)*44) {
+ if (sc == 0) {
+ slices.add(slice);
+ } else {
+ slices.add(""+slice+"");
+ }
+ slice = txt;
+ } else {
+ slice += "。" + txt;
+ }
+ }
+ }
+ }
+ if (slice.length() != 0) {
+ if (slice.contains(""+slice+"");
+ } else {
+ slices.add(slice);
+ }
+ }
+ return slices.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
+ }
+ private static void dealTencentLongText(boolean biaoinMarkExist, String txt, int bound, List slices) {
+ if (biaoinMarkExist) {
+ HashMap biaoyinArea = new HashMap<>();
+ int start = txt.indexOf("", start+31);
+ biaoyinArea.put(start, end+9);
+ start = txt.indexOf("= txt.length()) {
+ String s = txt.substring(commaIndex);
+ if (keyArr[keyArr.length-1] >= commaIndex) {
+ s = ""+s+"";
+ }
+ slices.add(s);
+ break;
+ }
+ boolean sliceBiaoyinExist = false;
+ int e;
+ for (Integer integer : keyArr) {
+ if (integer < commaIndex) {
+ continue;
+ }
+ if (integer < end) {
+ sliceBiaoyinExist = true;
+ e = biaoyinArea.get(integer);
+ if (e >= end) {
+ end = e + 1;
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ if (sliceBiaoyinExist) {
+ slices.add(""+txt.substring(commaIndex, end)+"");
+ } else {
+ slices.add(txt.substring(commaIndex, end));
+ }
+ commaIndex = end;
+ }
+ } else {
+ int commaIndex = 0;
+ while (commaIndex < txt.length()) {
+ slices.add(txt.substring(commaIndex, commaIndex+bound >= txt.length() ? txt.length() : commaIndex+bound));
+ commaIndex += bound;
+ }
}
}
- private static void sliceText(String text, int bound) {
+ private static List sliceText(String text, int bound) {
List slices = new ArrayList<>();
// ??。;.!!
- String[] arr = text.split("[。.]");
+ String[] arr = text.split("[。.??;!!]");
String slice = "";
for (String txt: arr) {
txt = txt.trim();
if (txt.length() == 0) {
continue;
- } else if (txt.length() >= bound) {
+ }
+ 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]))) {
-
+ String[] commaSlice = txt.split("[,,]");
+ if (commaSlice.length == 1 || (commaSlice.length == 2 && StringUtils.isAnyBlank(commaSlice[0], commaSlice[1]))) {
+ int commaIndex = 0;
+ while (commaIndex < txt.length()) {
+ slices.add(txt.substring(commaIndex, commaIndex+bound >= txt.length() ? txt.length() : commaIndex+bound));
+ commaIndex += bound;
+ }
+ } else {
+ for (String comma: commaSlice) {
+ if (StringUtils.isBlank(comma)) {
+ continue;
+ }
+ if (comma.length() > bound) {
+ if (slice.length() > 0) {
+ slices.add(slice);
+ slice = "";
+ }
+ int commaIndex = 0;
+ while (commaIndex < comma.length()) {
+ slices.add(comma.substring(commaIndex, commaIndex+bound >= comma.length() ? comma.length() : commaIndex+bound));
+ commaIndex += bound;
+ }
+ } else if (slice.length() + comma.length() >= bound) {
+ if (slice.length() > 0) {
+ slices.add(slice);
+ }
+ slice = comma;
+ } else {
+ if (slice.length() == 0) {
+ slice += comma;
+ } else {
+ slice += "," + comma;
}
}
}
}
-
- }
- if (slice.length() > bound) {
-
} else {
- slices.add(txt);
+ if (slice.length()+txt.length() >= bound) {
+ if (slice.length() > 0) {
+ slices.add(slice);
+ }
+ slice = txt;
+ } else {
+ if (slice.length() == 0) {
+ slice += txt;
+ } else {
+ slice += "。" + txt;
+ }
+ }
}
}
+ slices.add(slice);
+ return slices.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
}
private static void sliceRequestThird(ArrayDeque deque, int per, String filepath) {
@@ -593,6 +951,8 @@ public class ThirdPartyService {
// 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");
+// xunFeiTTS("xiaoyan", "今天是个好天气。佳人微醺,现在的她充满活力,要夸夸她吗", "/home/yf01/下载/audioCut/tecentXunFei06.wav");
+ String txt = "记者从天津滨海新区相关部门获悉,天津南环铁路桥坍塌事故现场救援搜救任务已经于11月1日18时完成。截至目前,事故已造成8人遇难,其中5人现场遇难,3人经医院全力";
+ System.out.println(sliceText(txt, 45));
}
}