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