Commit fdc76310 by 苗权威

11.04

parent 8eea4ec4
......@@ -204,6 +204,43 @@ public class CallPython {
return null;
}
public static String ffmpegExecuteGetResponse(String arg) {
ProcessBuilder processBuilder = new ProcessBuilder(arg.split(" "));
processBuilder.redirectErrorStream(true); //错误输出流合并到标准输出流中
StringBuilder builder = new StringBuilder();
Process process = null;
try {
//long startTime = System.currentTimeMillis();
process = processBuilder.start();
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
if (process.exitValue() != 0) {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
if (builder.length() > 0) {
log.error("ffmpegExecuteGetResponse 执行出错:{}",builder.toString());
return null;
}
} else {
while ((line = reader.readLine()) != null) {
builder.append(line);
}
if (builder.length() != 0){
return builder.toString();
}
}
//log.info(Thread.currentThread().getName()+"耗时:"+(System.currentTimeMillis()-startTime));
} catch (IOException | InterruptedException e) {
log.info("Error while running ffmpegExecuteGetResponse. {}",e.getMessage());
return null;
} finally {
if (process != null) process.destroy();
}
return null;
}
public static String ffmpegExecute(String arg) {
// log.warn("ffmpegExecute: "+arg);
ProcessBuilder processBuilder = new ProcessBuilder(arg.split(" "));
......
......@@ -60,8 +60,9 @@ public interface TTSConstants {
}
interface ALI_TTS {
String ACCESS_KEY_ID = "";
String ACCESS_KEY_SECRET = "";
String APP_KEY = "icp3h7cg9bmZ9jeL";
String ACCESS_KEY_ID = "LTAI4G1dvpMi65PwN3WKCjVj";
String ACCESS_KEY_SECRET = "R0J13fEPe1CYyC6pQTOLeiO1nO3pqN";
}
interface Audio {
......
package ai.qiwu.com.tts_service.common.pcm;
import ai.qiwu.com.tts_service.common.CallPython;
import ai.qiwu.com.tts_service.service.baidu.ThirdPartyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
......@@ -50,7 +52,19 @@ public class Pcm2Wav {
// text = text.substring(7, text.length()-8);
// System.out.println(ThirdPartyService.proTencentTextSlice(text, 6));
String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) * 1000L));
System.out.println("Token有效期的北京时间:" + expireDate);
// String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8")) * 1000L));
// String expireDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(1604573187*1000L));
// System.out.println("Token有效期的北京时间:" + expireDate);
// String s = CallPython.ffmpegExecuteGetResponse("ffmpeg -i /home/yf01/下载/audioCut/changeVolumn.mp3 -filter_complex volumedetect -c:v copy -f null /dev/null");
// if (StringUtils.isNotBlank(s)) {
// int i = s.lastIndexOf("mean_volume");
// if (i != -1) {
// s = s.substring(i+12, s.indexOf("dB",i+12)+2);
// System.out.println("="+s);
// }
// }
System.out.println(String.format("%.1f",0.23));;
}
}
......@@ -2,6 +2,7 @@ package ai.qiwu.com.tts_service.controller;
import ai.qiwu.com.tts_service.common.*;
import ai.qiwu.com.tts_service.pojo.*;
import ai.qiwu.com.tts_service.pojo.third.ChangeRecordVolume;
import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
import ai.qiwu.com.tts_service.repository.SpeakerInfoRepository;
import ai.qiwu.com.tts_service.service.*;
......@@ -238,6 +239,10 @@ public class TTSController {
String tid = mulRequest.getParameter("tid");
String sampleRate = mulRequest.getParameter("sampleRate");
String bitRate = mulRequest.getParameter("bitRate");
Boolean customText = StringUtils.isBlank(mulRequest.getParameter("customText")) ? false : Boolean.valueOf(mulRequest.getParameter("customText"));
if (Boolean.TRUE.equals(customText)) {
tid = "-"+tid;
}
UploadOneSenData data = new UploadOneSenData(Integer.valueOf(tid), botName, npcName, text, file);
data.setBitRate(bitRate);
data.setSampleRate(StringUtils.isBlank(sampleRate) ? 44100 : Integer.parseInt(sampleRate));
......@@ -251,8 +256,13 @@ public class TTSController {
}
@GetMapping("/api/upload/record/one_sen")
public ServerResponse getAudioConfig(String botName, String npcName, String text) {
return ttService.getOneSenAudioConfig(botName, npcName, text);
public ServerResponse getAudioConfig(String botName, String npcName, String text, @RequestParam(required = false) String onlyCheckExist) {
return ttService.getOneSenAudioConfig(botName, npcName, text, onlyCheckExist);
}
@PutMapping("/api/record/volume")
public ServerResponse changeRecordVolume(@RequestBody ChangeRecordVolume volume) {
return ttService.changeRecoedVolume(volume);
}
// @GetMapping("/api/del/all/up")
......@@ -374,6 +384,34 @@ public class TTSController {
ttService.delOneSen(data, response, head);
}
@DeleteMapping("/api/delete/one/audio")
public void delOneParticularAudio(String text, String npcName, String mood,
String person, String botAccount, String secret) {
if (StringUtils.startsWith(secret, "qiwu") && secret.length() == 8) {
String fileName = TTSUtils.buildMP3Filename(text);
if (StringUtils.isBlank(mood)) {
String path = Initialize.AUDIO_DIR+File.separator+botAccount
+File.separator+Initialize.UPLOADED_DIR+File.separator+npcName+File.separator+fileName;
try {
Files.deleteIfExists(Paths.get(path));
Files.deleteIfExists(Paths.get(path+".b64"));
} catch (IOException e) {
}
} else {
String pathPrefix = Initialize.AUDIO_DIR+File.separator+botAccount
+File.separator+person+File.separator+mood+File.separator;
try {
Files.deleteIfExists(Paths.get(pathPrefix+fileName));
Files.deleteIfExists(Paths.get(pathPrefix+fileName.substring(0, fileName.lastIndexOf("."))+".wav"));
Files.deleteIfExists(Paths.get(pathPrefix+fileName+".b64"));
} catch (IOException e) {
}
}
}
}
/**
* 合成后的回调
* @param file 文件
......
package ai.qiwu.com.tts_service.pojo.third;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* painter
* 20-11-4 下午9:13
*/
@Getter
@Setter
@ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class ChangeRecordVolume {
private String botName;
private String npcName;
private String text;
private Float volume;
}
......@@ -15,4 +15,5 @@ public class AudioConfigInfo {
private String duration;
private String fileSize;
private String bitRate;
private String meanVolume;
}
......@@ -125,7 +125,7 @@ public class Initialize implements InitializingBean {
/**
* 人工上传目录
*/
private static final String UPLOADED_DIR;
public static final String UPLOADED_DIR;
/**
* 删除缓存回调地址
*/
......@@ -257,6 +257,8 @@ public class Initialize implements InitializingBean {
THIRD_PARTY_WITH_ITS_PER.put("XunFei4", "aisjinger"); //讯飞小婧
THIRD_PARTY_WITH_ITS_PER.put("XunFei5", "aisbabyxu"); //讯飞许小宝
THIRD_PARTY_WITH_ITS_PER.put("Alyun1", "Xiaoyun"); //阿里小云
xunfeiUseSSMLPerson.add("XunFei1");
tencentProEnglishPerson.add("101050");
......
......@@ -45,13 +45,13 @@ public class LieHuSchedule {
// LIE_HU_TOKEN_HEADER.put("Content-Type", "application/json");
}
@Scheduled(fixedDelay = 1800000)
@Scheduled(fixedDelay = 3600000)
public void scheduleALiTTSToken() {
if (accessToken == null) {
accessToken = new AccessToken(TTSConstants.ALI_TTS.ACCESS_KEY_ID, TTSConstants.ALI_TTS.ACCESS_KEY_SECRET);
try {
accessToken.apply();
log.warn("阿里TTS token 超时时间:"+accessToken.getExpireTime());
log.warn("阿里TTS token 超时时间:{}, token:{}",accessToken.getExpireTime(), accessToken.getToken());
nlsClient = new NlsClient(accessToken.getToken());
} catch (IOException e) {
log.error(ExceptionUtils.getStackTrace(e));
......
......@@ -2,6 +2,7 @@ package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.*;
import ai.qiwu.com.tts_service.pojo.*;
import ai.qiwu.com.tts_service.pojo.third.ChangeRecordVolume;
import ai.qiwu.com.tts_service.pojo.upload.AudioConfigInfo;
import ai.qiwu.com.tts_service.pojo.upload.UploadCallbackResponse;
import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData;
......@@ -1492,7 +1493,39 @@ public class TTService {
initialize.updateCache();
}
public ServerResponse getOneSenAudioConfig(String botName, String npcName, String text) {
public ServerResponse changeRecoedVolume(ChangeRecordVolume recordVolume) {
if (StringUtils.isAnyBlank(recordVolume.getBotName(), recordVolume.getNpcName()) || recordVolume.getVolume() == null || recordVolume.getVolume() <= 0) {
return ServerResponse.createByErrorEnum(ResponseCode.DATA_IS_WRONG);
}
if (recordVolume.getVolume() > 5) {
recordVolume.setVolume(5f);
}
String volume = String.format("%.1f",recordVolume.getVolume());
String command = "sox -v "+ volume+" ";
if (StringUtils.isBlank(recordVolume.getText())) {
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));
} catch (Exception e) {
log.error("changeRecoedVolume error:{}, recordVolume:{}",e, recordVolume);
return ServerResponse.createByErrorEnum(ResponseCode.ERROR);
}
} else {
String path = StringUtils.join(new String[]{Initialize.getAudioDir(), recordVolume.getBotName(),
Initialize.getUploadedDir(), recordVolume.getNpcName(), TTSUtils.buildMP3Filename(recordVolume.getText())},File.separator);
if (!Files.exists(Paths.get(path))) {
return ServerResponse.createByErrorMessage("没有找到文本的人工语音文件,请确定您已上传过该文件");
}
CallPython.soxiGetAudioConfig(command + path + " " + path);
}
return ServerResponse.createBySuccess();
}
public ServerResponse getOneSenAudioConfig(String botName, String npcName, String text, String onlyCheckExist) {
if (StringUtils.isAnyBlank(botName, npcName, text)) {
return ServerResponse.createByErrorEnum(ResponseCode.DATA_IS_WRONG);
}
......@@ -1501,6 +1534,9 @@ public class TTService {
if (!Files.exists(Paths.get(path))) {
return ServerResponse.createByErrorMessage("没有找到文本的人工语音文件,请确定您已上传过该文件");
}
if (StringUtils.isNotBlank(onlyCheckExist)) {
return ServerResponse.createBySuccess();
}
String command = "soxi "+path;
String response = CallPython.soxiGetAudioConfig(command);
if (StringUtils.isNotBlank(response)) {
......@@ -1521,6 +1557,14 @@ public class TTService {
config.setDuration(duration);
config.setFileSize(fileSize);
config.setSampleRate(sampleRate);
String s = CallPython.ffmpegExecuteGetResponse("ffmpeg -i "+ path +" -filter_complex volumedetect -c:v copy -f null /dev/null");
if (StringUtils.isNotBlank(s)) {
int i = s.lastIndexOf("mean_volume");
if (i != -1) {
s = s.substring(i+12, s.indexOf("dB",i+12)+2);
config.setMeanVolume(s);
}
}
return ServerResponse.createBySuccess(config);
}
return ServerResponse.createBySuccess(response);
......
......@@ -152,6 +152,9 @@ public class ThirdPartyService {
}
return tecentTTS(per, text, filepath);
}
case "Alyun" : {
return aliTTS(per, text, filepath);
}
// 最大长度需小于8000字节,约2000汉字
case "XunFe": {
try {
......@@ -208,8 +211,8 @@ public class ThirdPartyService {
SpeechSynthesizer synthesizer = null;
try {
//创建实例,建立连接。
synthesizer = new SpeechSynthesizer(LieHuSchedule.nlsClient, getSynthesizerListener());
synthesizer.setAppKey(TTSConstants.ALI_TTS.ACCESS_KEY_ID);
synthesizer = new SpeechSynthesizer(LieHuSchedule.nlsClient, getSynthesizerListener(filepath));
synthesizer.setAppKey(TTSConstants.ALI_TTS.APP_KEY);
//设置返回音频的编码格式
synthesizer.setFormat(OutputFormatEnum.WAV);
//设置返回音频的采样率
......@@ -231,6 +234,7 @@ public class ThirdPartyService {
//等待语音合成结束
synthesizer.waitForComplete();
log.info("tts stop latency " + (System.currentTimeMillis() - start) + " ms");
return true;
} catch (Exception e) {
log.error(ExceptionUtils.getStackTrace(e));
} finally {
......@@ -239,6 +243,7 @@ public class ThirdPartyService {
synthesizer.close();
}
}
return false;
}
private static SpeechSynthesizerListener getSynthesizerListener(String filePath) {
......@@ -279,6 +284,9 @@ public class ThirdPartyService {
try {
fout.close();
} catch (Exception e){}
try {
Files.deleteIfExists(Paths.get(filePath));
} catch (Exception e){}
log.error("阿里TTS下载失败,task_id:{}, status:{}, status_text:{}", response.getTaskId(), response.getStatus(), response.getStatusText());
}
};
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment