From 4675c21252d886860aea52cea472c3ed03d05b18 Mon Sep 17 00:00:00 2001
From: 苗权威 <1160292058@qq.com>
Date: Fri, 6 Nov 2020 23:02:36 +0800
Subject: [PATCH] 11.06
---
.idea/workspace.xml | 419 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
tts_service/src/main/java/ai/qiwu/com/tts_service/common/OkHttp3Utils.java | 80 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSConstants.java | 15 +++++++--------
tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java | 1 +
tts_service/src/main/java/ai/qiwu/com/tts_service/service/LieHuSchedule.java | 5 +++--
tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java | 57 +++++++++++++++++++++++++++++++++++++++++++++++----------
tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTServiceEdition2.java | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
tts_service/src/main/java/ai/qiwu/com/tts_service/service/baidu/ThirdPartyService.java | 32 +++++++++++++++++++-------------
8 files changed, 388 insertions(+), 305 deletions(-)
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index 40a471d..5c3c5d7 100644
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -6,9 +6,9 @@
-
-
-
+
+
+
@@ -52,54 +52,41 @@
-
-
+
+
+
+
-
-
+
+
-
-
+
+
-
+
+
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
-
+
+
-
+
+
@@ -108,17 +95,17 @@
-
-
+
+
-
+
-
-
+
+
@@ -126,32 +113,28 @@
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
+
@@ -169,14 +152,6 @@
- name
- sliceRequestThird
- PERSON_INFO_ONLINE
- cutedPaths
- substring
- tecentAITTS
- 44
- text
keySet
slices
slice.length
@@ -186,8 +161,6 @@
nls
token
AUDIO_DIR
- successUpLoadFileIds
- record_callback_url
sox
api/upload
/api/upload/record/one_sen
@@ -198,7 +171,17 @@
THIRD_PARTY_WITH_ITS_PER
speakerInfoRepository
tryAcquire
+ tid
+ delCacheCallbackUrl
+ requestTemplate
+ codeWithData
+ headers
+ request
data
+ record_callback_url
+ usDir
+ successUpLoadFileIds
+ noeTextSameId
!CollectionUtils.isEmpty
@@ -217,7 +200,6 @@
@@ -299,10 +282,10 @@
-
-
-
-
+
+
+
+
@@ -311,85 +294,7 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
@@ -399,7 +304,7 @@
-
+
@@ -435,7 +340,7 @@
-
+
@@ -558,9 +463,9 @@
+
-
@@ -794,29 +699,31 @@
-
+
+
+
-
+
-
+
-
+
-
-
+
+
@@ -824,7 +731,7 @@
-
+
@@ -836,7 +743,7 @@
-
+
@@ -893,57 +800,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -1108,13 +964,6 @@
-
-
-
-
-
-
-
@@ -1165,20 +1014,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -1238,6 +1073,13 @@
+
+
+
+
+
+
+
@@ -1245,6 +1087,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
@@ -1256,47 +1130,43 @@
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
+
+
-
-
+
+
+
+
@@ -1304,17 +1174,54 @@
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
+
+
+
+
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 5f65536..d69e517 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
@@ -9,9 +9,13 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.CollectionUtils;
+import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -35,14 +39,80 @@ public class OkHttp3Utils {
.build();
/**
- * 客户端,超时时间设为10s
+ * 客户端,超时时间设为15s
*/
public static final OkHttpClient ShortTimeoutClient = new OkHttpClient.Builder()
- .connectTimeout(10, TimeUnit.SECONDS)
- .readTimeout(10, TimeUnit.SECONDS)
- .writeTimeout(10, TimeUnit.SECONDS)
+ .connectTimeout(15, TimeUnit.SECONDS)
+ .readTimeout(15, TimeUnit.SECONDS)
+ .writeTimeout(15, TimeUnit.SECONDS)
.build();
+ public static int postTTSEdition2(String url, Map headers,
+ String requestJsonStr, String path, boolean longTime) {
+ OkHttpClient timeoutClient;
+ if (longTime) {
+ timeoutClient = client;
+ } else {
+ timeoutClient = ShortTimeoutClient;
+ }
+
+ try {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+
+ Headers.Builder headBuilder = request.headers().newBuilder();
+
+ Iterator> headIterator = headers.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
+
+ builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
+ Response response = timeoutClient.newCall(builder.build()).execute();
+ try (ResponseBody body = response.body()){
+ int code = response.code();
+ if (code == HttpServletResponse.SC_OK) {
+ try (BufferedSink sink = Okio.buffer(Okio.sink(new File(path)))){
+ sink.writeAll(Objects.requireNonNull(body).source());
+ }
+ }
+ return code;
+ }catch (SocketTimeoutException e) {
+ log.error("捕获到SocketTimeoutException:{}", e.toString());
+ client.dispatcher().cancelAll();
+ client.connectionPool().evictAll();
+ }
+ } catch (Exception e) {
+ log.error("postTTSEdition2 error:{}, path:{}", e, path);
+ }
+ return 0;
+ }
+
+ public static String getTTSeDITION2(String url, Map params, Map header) throws IOException {
+ Request.Builder builder = new Request.Builder();
+ Request request = builder.url(url).build();
+ HttpUrl.Builder urlBuild = request.url().newBuilder();
+ Headers.Builder headerBuilder = request.headers().newBuilder();
+
+ Iterator> headIterator = header.entrySet().iterator();
+ headIterator.forEachRemaining(e -> headerBuilder.add(e.getKey(), e.getValue()));
+
+ Iterator> paramsIterator = params.entrySet().iterator();
+ paramsIterator.forEachRemaining(e -> urlBuild.addQueryParameter(e.getKey(), e.getValue()));
+
+ builder.url(urlBuild.build()).headers(headerBuilder.build());
+
+ Response response = client.newCall(builder.build()).execute();
+ try (ResponseBody body = response.body()){
+ return body.string();
+ } catch (SocketTimeoutException e) {
+ log.error("getTTSeDITION2 捕获到SocketTimeoutException:{}", e);
+ client.dispatcher().cancelAll();
+ client.connectionPool().evictAll();
+ }
+ return null;
+ }
+
+ // ================================================
+
/**
* Get请求
* @param url 请求地址
@@ -252,7 +322,7 @@ public class OkHttp3Utils {
headIterator.forEachRemaining(e -> headBuilder.add(e.getKey(), e.getValue()));
builder.headers(headBuilder.build()).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestJsonStr));
- ResponseCodeWithData codeWithData = null;
+ ResponseCodeWithData codeWithData;
Response response = timeoutClient.newCall(builder.build()).execute();
try (ResponseBody body = response.body()){
//log.info("doPostTimeout请求返回:{}", response.code());
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 1d65886..84bf12e 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
@@ -23,11 +23,8 @@ public interface TTSConstants {
String TTS_REMOTE_LOCALHOST = "localhost";
interface BAI_DU {
-// String APP_ID = "16998411";
String APP_ID = "16424686";
-// String API_KEY = "bHlKRYe9d5o7Ad2z2D5aGiVw";
String API_KEY = "YzZhZlb9lDnj8W4Z9GpsFQFo";
-// String SECRET_KEY = "f5bGP0PapVqSdl8gAOKGawHGlsSnHulB";
String SECRET_KEY = "Era6sREv5lgnOTpbcChmpruLZGY6C6Q9";
}
@@ -42,8 +39,10 @@ public interface TTSConstants {
}
interface TENCENT_AUDIO_ID {
- String APP_ID = "2159149523";
- String App_Key_WITH_PREFIX = "&app_key=lqpqxEo6p2xQSILQ";
+// String APP_ID = "2159149523";
+// String App_Key_WITH_PREFIX = "&app_key=lqpqxEo6p2xQSILQ";
+ String APP_ID = "2159448906";
+ String App_Key_WITH_PREFIX = "&app_key=7Ab1JbKljViyyXhf";
}
interface TENCENT_PROFESSION_TTS_ID {
@@ -60,9 +59,9 @@ public interface TTSConstants {
}
interface ALI_TTS {
- String APP_KEY = "icp3h7cg9bmZ9jeL";
- String ACCESS_KEY_ID = "LTAI4G1dvpMi65PwN3WKCjVj";
- String ACCESS_KEY_SECRET = "R0J13fEPe1CYyC6pQTOLeiO1nO3pqN";
+ String APP_KEY = "8nUeDWYW24K1KJos";
+ String ACCESS_KEY_ID = "LTAI4GGsz5h2UPxsL558pdnG";
+ String ACCESS_KEY_SECRET = "jSon2xkuuFquygYzP8Mwj6jMmP46PP";
}
interface Audio {
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java
index e23a680..a1149bc 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/upload/UploadOneSenData.java
@@ -22,6 +22,7 @@ public class UploadOneSenData {
private Integer sampleRate = 44100;
private String bitRate = "64K";
private MultipartFile file;
+ private Boolean customText;
public UploadOneSenData() {
}
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 fc388b6..228768f 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
@@ -31,7 +31,7 @@ public class LieHuSchedule {
// private static final HashMap LIE_HU_TOKEN_HEADER;
private static String LIE_HU_TOKEN;
- public static volatile NlsClient nlsClient = new NlsClient("99eccbe5318741b594c4860d0a98f2c1");
+ public static volatile NlsClient nlsClient = new NlsClient("dd5b063d26014dde807dee21368d1478");
private static volatile AccessToken accessToken;
static {
@@ -45,7 +45,8 @@ public class LieHuSchedule {
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
-// @Scheduled(fixedDelay = 3600000)
+// @Scheduled(fixedDelay = 3600000, initialDelay = 3600000)
+ @Scheduled(fixedDelay = 3600000)
public void scheduleALiTTSToken() {
if (accessToken == null) {
accessToken = new AccessToken(TTSConstants.ALI_TTS.ACCESS_KEY_ID, TTSConstants.ALI_TTS.ACCESS_KEY_SECRET);
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
index ebf19c5..5c26fa2 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -15,6 +15,7 @@ import org.apache.commons.csv.CSVRecord;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@@ -30,6 +31,7 @@ import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -1507,9 +1509,21 @@ public class TTService {
String dir = StringUtils.join(new String[]{Initialize.getAudioDir(), recordVolume.getBotName(),
Initialize.getUploadedDir(), recordVolume.getNpcName()},File.separator);
try {
- Files.list(Paths.get(dir)).filter(path -> StringUtils.endsWith(path.getFileName().toString(), ".mp3"))
- .map(path -> path.toAbsolutePath().toString())
- .forEach(path -> CallPython.soxiGetAudioConfig(command + path + " " + path));
+ Path dirPt = Paths.get(dir);
+ if (Files.exists(dirPt)) {
+ Files.list(dirPt).filter(path -> StringUtils.endsWith(path.getFileName().toString(), ".mp3"))
+ .map(path -> path.toAbsolutePath().toString())
+ .forEach(path -> {
+ String tempPath = path.substring(0, path.lastIndexOf("."))+"_vol.mp3";
+ try {
+ CallPython.soxiGetAudioConfig(command + path + " " + tempPath);
+ Files.move(Paths.get(tempPath), Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
+ } catch (Exception e) {
+ log.error("changeRecoedVolume move:{}, path:{}", e, path);
+ new File(tempPath).delete();
+ }
+ });
+ }
} catch (Exception e) {
log.error("changeRecoedVolume error:{}, recordVolume:{}",e, recordVolume);
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
@@ -1520,7 +1534,15 @@ public class TTService {
if (!Files.exists(Paths.get(path))) {
return ServerResponse.createByErrorMessage("没有找到文本的人工语音文件,请确定您已上传过该文件");
}
- CallPython.soxiGetAudioConfig(command + path + " " + path);
+ String tempPath = path.substring(0, path.lastIndexOf("."))+"_vol.mp3";
+ try {
+ CallPython.soxiGetAudioConfig(command + path + " " + tempPath);
+ Files.move(Paths.get(tempPath), Paths.get(path), StandardCopyOption.REPLACE_EXISTING);
+ } catch (Exception e) {
+ log.error("changeRecoedVolume move:{}, path:{}", e, path);
+ new File(tempPath).delete();
+ return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
+ }
}
return ServerResponse.createBySuccess();
}
@@ -1622,7 +1644,8 @@ public class TTService {
String folder = StringUtils.join(new String[]{Initialize.getAudioDir(), data.getBotName(),
Initialize.getUploadedDir(), data.getNpcName()},File.separator);
// absolute filepath
- final String filename = StringUtils.join(new String[]{folder, TTSUtils.buildMP3Filename(data.getText())}, File.separator);
+ String mp3Name;
+ final String filename = StringUtils.join(new String[]{folder, (mp3Name=TTSUtils.buildMP3Filename(data.getText()))}, File.separator);
// log.info("filepath:{}",filename);
// 删除之前已存在的文件
if (TTSUtils.doesFileExist(filename) ) {
@@ -1675,7 +1698,13 @@ public class TTService {
headers.put("Content-Type","application/json; charset=utf-8");
// String jsonData = JSON.toJSONString(new int[]{data.getTid()});
// log.warn("getRecord_callback_url json data:{}, url:{}",jsonData, Initialize.getRecord_callback_url());
- msg = OkHttp3Utils.doPostJsonStr(Initialize.getRecord_callback_url(), JSON.toJSONString(new int[]{data.getTid()}), headers);
+ String id;
+ if (data.getTid() < 0) {
+ id = String.valueOf(data.getTid());
+ } else {
+ id = data.getTid() + "_" + mp3Name;
+ }
+ msg = OkHttp3Utils.doPostJsonStr(Initialize.getRecord_callback_url(), JSON.toJSONString(new String[]{id}), headers);
} catch (Exception e) {
msg = "post record_callback_url error";
log.error("post record_callback_url error:{}",ExceptionUtils.getStackTrace(e));
@@ -2151,6 +2180,7 @@ public class TTService {
// }
// });
try {
+ successUpLoadFileIds = successUpLoadFileIds.stream().filter(StringUtils::isNotBlank).collect(Collectors.toSet());
log.info("打包上传成功id个数:{}",successUpLoadFileIds.size());
String requestCall = JSON.toJSONString(successUpLoadFileIds);
//log.info("requestCall:{}",requestCall);
@@ -2160,7 +2190,7 @@ public class TTService {
String str = OkHttp3Utils.doPostJsonStr(Initialize.getRecord_callback_url(), requestCall, headers);
if (str != null) {
UploadCallbackResponse callbackResponse = JSON.parseObject(str, UploadCallbackResponse.class);
- if (callbackResponse == null || callbackResponse.getCode() != 1) {
+ if (callbackResponse == null || !NumberUtils.INTEGER_ONE.equals(callbackResponse.getCode())) {
log.warn("打包上传回调返回信息:{}",str);
TTServiceUtil.buildUploadResponse(response, new TTSResponse(500, "打包上传回调出现错误"), 500);
return zipFolder;
@@ -2217,8 +2247,9 @@ public class TTService {
return;
}
// audio_dir/botname/record/npcname/xxx.mp3
+ String mp3Name;
final String filePath = StringUtils.join(Arrays.asList(Initialize.getAudioDir(), data.getBotName(),
- Initialize.getUploadedDir(), data.getNpcName(), TTSUtils.buildMP3Filename(data.getText())), File.separator);
+ Initialize.getUploadedDir(), data.getNpcName(), (mp3Name=TTSUtils.buildMP3Filename(data.getText()))), File.separator);
boolean result;
// 删除文件
if (TTSUtils.doesFileExist(filePath)) {
@@ -2230,14 +2261,20 @@ public class TTService {
}
// 删除成功回调接口/text/offline/delUpload/callback
if (result) {
- final int tid = data.getTid();
+
POOL.submit(() -> {
new File(new StringBuilder(filePath).append(".b64").toString()).delete();
try {
HashMap headers = new HashMap<>();
headers.put("Authorization", head);
headers.put("Content-Type","application/json; charset=utf-8");
- OkHttp3Utils.doPostJsonStr(Initialize.getDelRecordCallbackUrl(), JSON.toJSONString(new int[]{tid}), headers);
+ String tid;
+ if (Boolean.TRUE.equals(data.getCustomText())) {
+ tid = String.valueOf(-data.getTid());
+ } else {
+ tid = data.getTid()+"_"+mp3Name;
+ }
+ OkHttp3Utils.doPostJsonStr(Initialize.getDelRecordCallbackUrl(), JSON.toJSONString(new String[]{tid}), headers);
} catch (Exception e) {
log.error("delOneSen删除地址回调出错:{}",e.toString());
}
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 a0f0350..9af0b67 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
@@ -4,6 +4,7 @@ import ai.qiwu.com.tts_service.common.*;
import ai.qiwu.com.tts_service.pojo.*;
import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService;
import com.alibaba.fastjson.JSON;
+import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
@@ -13,6 +14,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
+import sun.rmi.runtime.Log;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
@@ -466,7 +468,8 @@ public class TTServiceEdition2 {
} else if (!fileExist) {
if (Initialize.OFFLINE_SERVER.equals(url)) {
data.setFormat("mp3");
- int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
+// int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
+ int status = OkHttp3Utils.postTTSEdition2(url, Collections.emptyMap(), JSON.toJSONString(data), filePath, false);
if (status != HttpServletResponse.SC_OK) {
log.info("直接下载人物{}的mp3文件失败,TEXT:{}",filePath,data.getText());
@@ -486,15 +489,26 @@ public class TTServiceEdition2 {
private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean getOnline) {
ResponseCodeWithData res;
// data.setMode("test");
- int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
- if (status == 0) res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "请求出错");
- else if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) {
- 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());
- status = ApachHttpUtils.audioPost(Initialize.AUDIO_GENERATE_SERVER, JSON.toJSONString(jumpedData), filePath);
+ String dataJsonStr;
+ int status = OkHttp3Utils.postTTSEdition2(url, Collections.emptyMap(), (dataJsonStr=JSON.toJSONString(data)), filePath, false);
+// int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
+ 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++;
+ try {
+ Thread.sleep(500*retryCount);
+ } catch (Exception e) {}
+ status = OkHttp3Utils.postTTSEdition2(url, Collections.emptyMap(), dataJsonStr, filePath, true);
+ if (status == HttpServletResponse.SC_OK) {
+ return new ResponseCodeWithData(status);
+ } else if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) {
+ return dealOfflineJump(data, getOnline, filePath);
+ }
+ } while (retryCount < 4);
+ log.error("requestTemplate尝试3次后仍失败:status:{}, text:{}, filePath:{}", status, data.getText(), filePath);
res = new ResponseCodeWithData(status);
} else {
res = new ResponseCodeWithData(status);
@@ -507,6 +521,41 @@ public class TTServiceEdition2 {
return res;
}
+ 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);
+ }
+
+// private ResponseCodeWithData requestTemplate(String url, GeneralMP3Data data, String filePath, boolean getOnline) {
+// ResponseCodeWithData res;
+//// data.setMode("test");
+// int status = ApachHttpUtils.audioPost(url, JSON.toJSONString(data), filePath);
+// if (status == 0) res = new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "请求出错");
+// else if (status == HttpServletResponse.SC_NOT_FOUND && Initialize.OFFLINE_SERVER.equals(url)) {
+// 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());
+// status = ApachHttpUtils.audioPost(Initialize.AUDIO_GENERATE_SERVER, JSON.toJSONString(jumpedData), filePath);
+// res = new ResponseCodeWithData(status);
+// } else {
+// res = new ResponseCodeWithData(status);
+// }
+//
+//// if ((res == null || res.getCode() != 200) && !"mp3".equals(data.getFormat())) {
+//// log.warn("requestTemplate:列户小雅兜底调用");
+//// res = dealThirdParty(data.getText(), "Liehu1", filePath);
+//// }
+// return res;
+// }
+
private ResponseCodeWithData changeSound(String wavFilename, double volume, double speed,
double pitch, String mp3FilePath) {
ResponseCodeWithData res = null;
@@ -901,7 +950,20 @@ public class TTServiceEdition2 {
if (result) {
return new ResponseCodeWithData(HttpServletResponse.SC_OK, "创建第三方wav文件成功");
}
- log.error("调用第三方生成wav文件失败");
+
+ int thirdFailRetryCount = 0;
+ do {
+ thirdFailRetryCount++;
+ try {
+ Thread.sleep(500*thirdFailRetryCount);
+ } catch (Exception e){}
+ result = ThirdPartyService.thirdPartyCall(text, Initialize.theThirdPartysPer(person), filepath, person);
+ if (result) {
+ return new ResponseCodeWithData(HttpServletResponse.SC_OK, "创建第三方wav文件成功");
+ }
+ } while (thirdFailRetryCount <4);
+
+ log.error("尝试3次后调用第三方生成wav文件失败:text:{}, person:{}", text, person);
return new ResponseCodeWithData(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "调用第三方生成wav文件失败");
}
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 a89e725..bd81992 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
@@ -77,7 +77,7 @@ public class ThirdPartyService {
clientProfile.setHttpProfile(httpProfile);
TTS_CLIENT = new TtsClient(CREDENTIAL, "ap-guangzhou", clientProfile);
- TENCENT_AI_TTS_LOCK = new Semaphore(2);
+ TENCENT_AI_TTS_LOCK = new Semaphore(10);
ALI_YUN_TTS_LOCK = new Semaphore(2);
}
@@ -268,7 +268,7 @@ public class ThirdPartyService {
try {
listener = new SpeechSynthesizerListener() {
FileOutputStream fout = new FileOutputStream(new File(filePath));
- private boolean firstRecvBinary = true;
+// private boolean firstRecvBinary = true;
//语音合成结束
@Override
public void onComplete(SpeechSynthesizerResponse response) {
@@ -282,11 +282,11 @@ public class ThirdPartyService {
@Override
public void onMessage(ByteBuffer message) {
try {
- if(firstRecvBinary) {
- //计算首包语音流的延迟,收到第一包语音流时,即可以进行语音播放,以提升响应速度(特别是实时交互场景下)。
- firstRecvBinary = false;
- log.info("tts first latency");
- }
+// if(firstRecvBinary) {
+// //计算首包语音流的延迟,收到第一包语音流时,即可以进行语音播放,以提升响应速度(特别是实时交互场景下)。
+// firstRecvBinary = false;
+// log.info("tts first latency");
+// }
byte[] bytesArray = new byte[message.remaining()];
message.get(bytesArray, 0, bytesArray.length);
fout.write(bytesArray);
@@ -581,7 +581,8 @@ public class ThirdPartyService {
}).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);
+// String result = ApachHttpUtils.get("https://api.ai.qq.com/fcgi-bin/aai/aai_tts", null, params);
+ String result = OkHttp3Utils.getTTSeDITION2("https://api.ai.qq.com/fcgi-bin/aai/aai_tts", params, Collections.emptyMap());
if (StringUtils.isBlank(result)) {
log.error("请求腾讯AI tts出错,结果为空:"+text);
} else {
@@ -599,7 +600,7 @@ public class ThirdPartyService {
}
}
return false;
- } catch (InterruptedException e) {
+ } catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
if (acquireSuccess) {
@@ -609,7 +610,7 @@ public class ThirdPartyService {
return false;
}
- private static boolean tecentYouTTS(String per, String text, String filepath) {
+ private static boolean tecentYouTTS(String per, String text, String filepath) throws IOException {
TreeMap params = new TreeMap<>();
params.put("app_id", TTSConstants.TENCENT_AUDIO_ID.APP_ID);
long secondStamp;
@@ -628,7 +629,8 @@ public class ThirdPartyService {
}).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_tta", null, params);
+// String result = ApachHttpUtils.get("https://api.ai.qq.com/fcgi-bin/aai/aai_tta", null, params);
+ String result = OkHttp3Utils.getTTSeDITION2("https://api.ai.qq.com/fcgi-bin/aai/aai_tta", params, Collections.emptyMap());
if (StringUtils.isBlank(result)) {
log.error("请求腾讯优图出错,结果为空:"+text);
} else {
@@ -1029,7 +1031,11 @@ public class ThirdPartyService {
// 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");
- String txt = "记者从天津滨海新区相关部门获悉,天津南环铁路桥坍塌事故现场救援搜救任务已经于11月1日18时完成。截至目前,事故已造成8人遇难,其中5人现场遇难,3人经医院全力";
- System.out.println(sliceText(txt, 45));
+// String txt = "记者从天津滨海新区相关部门获悉,天津南环铁路桥坍塌事故现场救援搜救任务已经于11月1日18时完成。截至目前,事故已造成8人遇难,其中5人现场遇难,3人经医院全力";
+// System.out.println(sliceText(txt, 45));
+ System.out.println(TTSUtils.buildMP3Filename("今天是"));
+ System.out.println(TTSUtils.buildMP3Filename("晴天"));
+ System.out.println(TTSUtils.buildMP3Filename("今天是\uD83C\uDD70晴天\uD83C\uDD71"));
+ System.out.println(TTSUtils.buildMP3Filename("今天是\uD83C\uDD70晴天\uD83C\uDD71还是\uD83C\uDD70阴天\uD83C\uDD71"));
}
}
--
libgit2 0.27.1