From f64a2e4c82ce55f7e40ddef03701ea348533b513 Mon Sep 17 00:00:00 2001
From: 苗权威 <1160292058@qq.com>
Date: Thu, 28 Nov 2019 14:50:32 +0800
Subject: [PATCH] 11.28
---
.idea/compiler.xml | 2 +-
.idea/workspace.xml | 754 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
tts_service/pom.xml | 35 +++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java | 9 ++++++++-
tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java | 4 ++--
tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java | 22 ++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java | 246 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java | 455 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java | 351 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java | 338 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java | 346 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java | 240 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java | 1 +
tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java | 20 +++++++++++++++-----
tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java | 34 ++++++++++++++++++++++++++++++----
tts_service/src/main/resources/deploy.properties | 16 ++++++++++++++++
tts_service/src/main/resources/static/jave-1.0.2.jar | Bin 0 -> 5868832 bytes
tts_service/src/main/resources/static/tritonus_share-0.3.6.jar | Bin 0 -> 105684 bytes
tts_service/src/main/resources/tts.properties | 16 ----------------
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java | 10 ++++++++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java | 6 ++++--
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java | 2 ++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/XiaoAiRequest.java | 4 ++++
xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java | 20 ++++++++++++--------
xiaoduhome/src/main/resources/templates/index.html | 2 +-
27 files changed, 2762 insertions(+), 457 deletions(-)
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java
create mode 100644 tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java
create mode 100755 tts_service/src/main/resources/deploy.properties
create mode 100644 tts_service/src/main/resources/static/jave-1.0.2.jar
create mode 100644 tts_service/src/main/resources/static/tritonus_share-0.3.6.jar
delete mode 100755 tts_service/src/main/resources/tts.properties
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
index 3cb42ad..8982f58 100755
--- a/.idea/compiler.xml
+++ b/.idea/compiler.xml
@@ -33,7 +33,7 @@
-
+
diff --git a/.idea/workspace.xml b/.idea/workspace.xml
index d8fcadc..92e4dae 100755
--- a/.idea/workspace.xml
+++ b/.idea/workspace.xml
@@ -10,18 +10,22 @@
+
-
-
-
+
+
+
+
+
+
-
-
+
-
-
+
+
+
@@ -64,76 +68,41 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
-
-
+
-
-
+
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
@@ -145,34 +114,13 @@
-
+
- response.body()
- filename
- fileName
- zipFolder
- j
- return
- session
- Session
- deviceId
- CACHE_XIAODU_REQUEST
- onLinkAccountSucceededEvent
- intentName
- EXCEPT_BOT_ACCOUNT
- dealDefaultIntent
- userId
- getUserId()
- ge
- getUserId
- botAcc
- response
- shouldEndSession
PlaybackStarted
onPlaybackStartedEvent
data
@@ -182,6 +130,27 @@
trim()
LAST_OUTTIME_RESULT
onSess
+ rootFolder
+ uploadFolder
+ botName
+ fDesiredSampleRate
+ targetFile
+ combineMp3Text2FilePath
+ file_ls
+ fTargetFrameRate
+ Rate
+ Config
+ nDesiredChannels
+ channelModeAsString
+ desiredEncoding
+ libmp3
+ audioHeader
+ desiredFileType
+ fTargetSampleRate
+ getSampleRate
+ mp3FrameHeader
+ audioInputStreamList
+ deal
OPENID_CACHE
@@ -198,26 +167,6 @@
@@ -266,15 +235,6 @@
-
-
-
-
-
-
-
-
-
@@ -289,9 +249,9 @@
-
-
-
+
+
+
@@ -303,8 +263,6 @@
-
-
@@ -315,69 +273,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
@@ -441,27 +336,12 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
@@ -475,7 +355,7 @@
-
+
@@ -486,13 +366,6 @@
-
-
-
-
-
-
-
@@ -500,6 +373,13 @@
+
+
+
+
+
+
+
@@ -507,12 +387,12 @@
-
+
-
-
-
-
+
+
+
+
@@ -528,12 +408,12 @@
-
-
-
+
+
+
-
+
@@ -541,12 +421,12 @@
-
-
-
+
+
+
-
+
@@ -554,12 +434,12 @@
-
-
+
+
-
+
@@ -567,12 +447,12 @@
-
-
-
+
+
+
-
+
@@ -903,10 +783,10 @@
-
-
-
+
+
+
@@ -931,10 +811,10 @@
+
+
+
-
-
-
@@ -1092,7 +972,12 @@
-
+
+
+
+
+
+
@@ -1102,7 +987,7 @@
-
+
@@ -1114,7 +999,8 @@
-
+
+
@@ -1127,13 +1013,13 @@
-
+
-
+
@@ -1144,7 +1030,7 @@
-
+
@@ -1164,385 +1050,419 @@
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
-
-
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
+
-
-
+
+
+
+
+
+
+
-
+
-
-
+
+
-
+
+
+
+
-
+
+
+
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
-
+
-
+
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
+
+
+
+
+
+
-
+
-
-
+
+
-
-
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
+
-
+
-
-
+
-
+
-
-
+
+
+
+
+
+
+
-
-
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
-
-
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
-
-
+
+
+
-
+
-
-
+
+
-
+
-
-
+
+
-
+
-
-
-
-
-
-
+
+
-
+
-
-
+
+
-
+
-
-
+
+
+
+
+
-
+
-
-
-
-
-
+
+
diff --git a/tts_service/pom.xml b/tts_service/pom.xml
index 7499546..767f79a 100755
--- a/tts_service/pom.xml
+++ b/tts_service/pom.xml
@@ -104,6 +104,38 @@
commons-csv
1.7
+
+
+
+
+
+
+
+
+ ws.schild
+ jave-all-deps
+ 2.7.1
+
+
+
+ org
+ jaudiotagger
+ 2.0.3
+
+
+ com.jave
+ jave
+ 1.0.2
+ system
+ ${project.basedir}/src/main/resources/static/jave-1.0.2.jar
+
+
+
+
+
+
+
+
@@ -112,6 +144,9 @@
org.springframework.boot
spring-boot-maven-plugin
+
+ true
+
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
index 07661b3..4b53436 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/CallPython.java
@@ -43,6 +43,13 @@ public class CallPython {
return result;
}
+ public static String wav2Mp3(String wavPath, String mp3Path) {
+ execute(new StringBuilder("sox ").append(wavPath).append(" ").append(mp3Path).toString());
+ if (TTSUtils.doesFileExist(mp3Path)) return mp3Path;
+ log.error("调用sox 转wav为mp3失败");
+ return null;
+ }
+
/**
* 调用python来合成mp3
* @param wav_filename wav文件地址
@@ -67,7 +74,7 @@ public class CallPython {
*/
public static void getPythonInterpreter() {
String interpreter = processUtil("pipenv run which python");
- log.info("获取的python解释器位置:{}", interpreter);
+ log.warn("获取的python解释器位置:{}", interpreter);
if (StringUtils.isNotBlank(interpreter)) INTERPRETER = interpreter;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
index 9372c1f..05395eb 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/Config.java
@@ -20,7 +20,7 @@ public class Config {
private static Properties properties;
static {
-// String filename = "tts.properties";
+// String filename = "deploy.properties";
// String filename = "ttsDidi.properties";
// String filename = "ttsTest.properties";
String filename = "deploy.properties";
@@ -29,7 +29,7 @@ public class Config {
// properties.load(new InputStreamReader(Objects.requireNonNull(Config.class.getClassLoader().getResourceAsStream(filename)), StandardCharsets.UTF_8));
String path = System.getProperty("java.class.path");
path = path.substring(0, path.lastIndexOf(File.separator)+1) + filename;
- log.info("配置文件:{}",path);
+ log.warn("配置文件:{}",path);
properties.load(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
} catch (Exception e) {
log.error("获取配置文件对象出错:{}", e.toString());
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
index daa1522..0ea4dee 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/TTSUtils.java
@@ -1,11 +1,14 @@
package ai.qiwu.com.tts_service.common;
+import ai.qiwu.com.tts_service.common.sound.SampleRateConverter;
import ai.qiwu.com.tts_service.pojo.TTSRequest;
import ai.qiwu.com.tts_service.service.Initialize;
+import ai.qiwu.com.tts_service.service.TTService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import javax.sound.sampled.AudioFileFormat;
@@ -482,9 +485,18 @@ public class TTSUtils {
*/
public static void combineMp3File(Collection filePathList, String targetFilepath)
throws IOException {
+ try {
+// List filePaths = SampleRateConverter.equalSampleRate(filePathList);
+// List filePaths = SampleRateConverter.equalWavData(filePathList);
+ List filePaths = SampleRateConverter.equalSampleRateUseFfmepg(filePathList);
+ if (!CollectionUtils.isEmpty(filePaths)) filePathList = filePaths;
+ } catch (Exception e) {
+ log.error("转换采样率出现错误:{}",e);
+ }
try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)))){
AudioEnumeration audioEnumeration = new AudioEnumeration<>();
for (String filepath : filePathList) {
+// log.warn(filepath);
if (filepath.equals(Initialize.getThirdParty())) {
continue;
}
@@ -499,6 +511,16 @@ public class TTSUtils {
outputStream.flush();
sequenceInputStream.close();
}
+ final List check = new ArrayList<>(filePathList);
+ TTService.POOL.submit(() -> {
+ for (String path: check) {
+ if (StringUtils.endsWith(path, SampleRateConverter.SUFFIX_MP3)) {
+ if (!new File(path).delete()) log.error("删除采样率mp3出错:{}",path);
+// String wavTempPath = path.substring(0, path.length()-8)+SampleRateConverter.SUFFIX_WAV;
+// if (!new File(wavTempPath).delete()) log.error("删除采样率wav出错:{}",wavTempPath);
+ }
+ }
+ });
}
/**
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java
new file mode 100644
index 0000000..fa0140b
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java
@@ -0,0 +1,208 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import javax.sound.sampled.*;
+
+/**
+ * @dateTime 19-11-23 下午2:24
+ */
+public class AudioCommon {
+
+ private static boolean DEBUG = false;
+
+
+
+ public static void setDebug(boolean bDebug)
+ {
+ DEBUG = bDebug;
+ }
+
+
+
+ /** TODO:
+ */
+ public static void listSupportedTargetTypes()
+ {
+ String strMessage = "Supported target types:";
+ AudioFileFormat.Type[] aTypes = AudioSystem.getAudioFileTypes();
+ for (int i = 0; i < aTypes.length; i++)
+ {
+ strMessage += " " + aTypes[i].getExtension();
+ }
+ out(strMessage);
+ }
+
+
+
+ /** Trying to get an audio file type for the passed extension.
+ This works by examining all available file types. For each
+ type, if the extension this type promisses to handle matches
+ the extension we are trying to find a type for, this type is
+ returned.
+ If no appropriate type is found, null is returned.
+ */
+ public static AudioFileFormat.Type findTargetType(String strExtension)
+ {
+ AudioFileFormat.Type[] aTypes = AudioSystem.getAudioFileTypes();
+ for (int i = 0; i < aTypes.length; i++)
+ {
+ if (aTypes[i].getExtension().equals(strExtension))
+ {
+ return aTypes[i];
+ }
+ }
+ return null;
+ }
+
+
+
+ /** TODO:
+ */
+ public static void listMixersAndExit()
+ {
+ out("Available Mixers:");
+ Mixer.Info[] aInfos = AudioSystem.getMixerInfo();
+ for (int i = 0; i < aInfos.length; i++)
+ {
+ out(aInfos[i].getName());
+ }
+ if (aInfos.length == 0)
+ {
+ out("[No mixers available]");
+ }
+ System.exit(0);
+ }
+
+
+
+ /** List Mixers.
+ Only Mixers that support either TargetDataLines or SourceDataLines
+ are listed, depending on the value of bPlayback.
+ */
+ public static void listMixersAndExit(boolean bPlayback)
+ {
+ out("Available Mixers:");
+ Mixer.Info[] aInfos = AudioSystem.getMixerInfo();
+ for (int i = 0; i < aInfos.length; i++)
+ {
+ Mixer mixer = AudioSystem.getMixer(aInfos[i]);
+ Line.Info lineInfo = new Line.Info(bPlayback ?
+ SourceDataLine.class :
+ TargetDataLine.class);
+ if (mixer.isLineSupported(lineInfo))
+ {
+ out(aInfos[i].getName());
+ }
+ }
+ if (aInfos.length == 0)
+ {
+ out("[No mixers available]");
+ }
+ System.exit(0);
+ }
+
+
+
+ /** TODO:
+ This method tries to return a Mixer.Info whose name
+ matches the passed name. If no matching Mixer.Info is
+ found, null is returned.
+ */
+ public static Mixer.Info getMixerInfo(String strMixerName)
+ {
+ Mixer.Info[] aInfos = AudioSystem.getMixerInfo();
+ for (int i = 0; i < aInfos.length; i++)
+ {
+ if (aInfos[i].getName().equals(strMixerName))
+ {
+ return aInfos[i];
+ }
+ }
+ return null;
+ }
+
+
+
+ /** TODO:
+ */
+ public static TargetDataLine getTargetDataLine(String strMixerName,
+ AudioFormat audioFormat,
+ int nBufferSize)
+ {
+ /*
+ Asking for a line is a rather tricky thing.
+ We have to construct an Info object that specifies
+ the desired properties for the line.
+ First, we have to say which kind of line we want. The
+ possibilities are: SourceDataLine (for playback), Clip
+ (for repeated playback) and TargetDataLine (for
+ recording).
+ Here, we want to do normal capture, so we ask for
+ a TargetDataLine.
+ Then, we have to pass an AudioFormat object, so that
+ the Line knows which format the data passed to it
+ will have.
+ Furthermore, we can give Java Sound a hint about how
+ big the internal buffer for the line should be. This
+ isn't used here, signaling that we
+ don't care about the exact size. Java Sound will use
+ some default value for the buffer size.
+ */
+ TargetDataLine targetDataLine = null;
+ DataLine.Info info = new DataLine.Info(TargetDataLine.class,
+ audioFormat, nBufferSize);
+ try
+ {
+ if (strMixerName != null)
+ {
+ Mixer.Info mixerInfo = getMixerInfo(strMixerName);
+ if (mixerInfo == null)
+ {
+ out("AudioCommon.getTargetDataLine(): mixer not found: " + strMixerName);
+ return null;
+ }
+ Mixer mixer = AudioSystem.getMixer(mixerInfo);
+ targetDataLine = (TargetDataLine) mixer.getLine(info);
+ }
+ else
+ {
+ if (DEBUG) { out("AudioCommon.getTargetDataLine(): using default mixer"); }
+ targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
+ }
+
+ /*
+ * The line is there, but it is not yet ready to
+ * receive audio data. We have to open the line.
+ */
+ if (DEBUG) { out("AudioCommon.getTargetDataLine(): opening line..."); }
+ targetDataLine.open(audioFormat, nBufferSize);
+ if (DEBUG) { out("AudioCommon.getTargetDataLine(): opened line"); }
+ }
+ catch (LineUnavailableException e)
+ {
+ if (DEBUG) { e.printStackTrace(); }
+ }
+ catch (Exception e)
+ {
+ if (DEBUG) { e.printStackTrace(); }
+ }
+ if (DEBUG) { out("AudioCommon.getTargetDataLine(): returning line: " + targetDataLine); }
+ return targetDataLine;
+ }
+
+
+ /** Checks if the encoding is PCM.
+ */
+ public static boolean isPcm(AudioFormat.Encoding encoding)
+ {
+ return encoding.equals(AudioFormat.Encoding.PCM_SIGNED)
+ || encoding.equals(AudioFormat.Encoding.PCM_UNSIGNED);
+ }
+
+
+ /** TODO:
+ */
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java
new file mode 100644
index 0000000..109b736
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java
@@ -0,0 +1,246 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import lombok.extern.slf4j.Slf4j;
+
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * 合并wav文件
+ * @dateTime 19-11-25 下午3:05
+ */
+@Slf4j
+public class AudioConcat {
+
+ private static final int MODE_NONE = 0;
+ private static final int MODE_MIXING = 1;
+ private static final int MODE_FLOATMIXING = 2;
+ private static final int MODE_CONCATENATION = 3;
+
+ /** Flag for debugging messages.
+ * If true, some messages are dumped to the console
+ * during operation.
+ */
+ private static boolean DEBUG = false;
+
+ public static void audioContact(List sourceList, String targetPath) {
+ AudioFormat audioFormat = null;
+ List audioInputStreamList = new ArrayList();
+
+ for (String path: sourceList)
+ {
+ File soundFile = new File(path);
+ AudioInputStream audioInputStream = null;
+ try
+ {
+ audioInputStream = AudioSystem.getAudioInputStream(soundFile);
+ }
+ catch (Exception e) {
+ log.error("合并时获取{}音频流出错",path);
+ return;
+ }
+
+ AudioFormat format = audioInputStream.getFormat();
+ if (audioFormat == null)
+ {
+ audioFormat = format;
+ if (DEBUG) { out("AudioConcat.main(): format: " + audioFormat); }
+ }
+ else if (!audioFormat.matches(format))
+ {
+ // TODO: try to convert
+ out("AudioConcat.main(): WARNING: AudioFormats don't match");
+ out("AudioConcat.main(): master format: " + audioFormat);
+ out("AudioConcat.main(): this format: " + format);
+ }
+ audioInputStreamList.add(audioInputStream);
+ }
+
+ AudioInputStream audioInputStream = new SequenceAudioInputStream(audioFormat, audioInputStreamList);
+ File outputFile = new File(targetPath);
+ try
+ {
+ AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+
+ if (DEBUG) { out("AudioConcat.main(): before exit"); }
+ System.exit(0);
+ }
+
+ public static void main(String[] args)
+ {
+ /** Mode of operation.
+ Determines what to do with the input files:
+ either mixing or concatenation.
+ */
+ int nMode = MODE_NONE;
+ String strOutputFilename = null;
+ AudioFormat audioFormat = null;
+ List audioInputStreamList = new ArrayList();
+
+ // int nExternalBufferSize = DEFAULT_EXTERNAL_BUFFER_SIZE;
+ // int nInternalBufferSize = AudioSystem.NOT_SPECIFIED;
+
+
+ /*
+ * Parsing of command-line options takes place...
+ */
+// Getopt g = new Getopt("AudioConcat", args, "hDcmfo:");
+// int c;
+// while ((c = g.getopt()) != -1)
+// {
+// switch (c)
+// {
+// case 'h':
+// printUsageAndExit();
+//
+// case 'o':
+// strOutputFilename = g.getOptarg();
+// if (DEBUG) { out("AudioConcat.main(): output filename: " + strOutputFilename); }
+// break;
+//
+// case 'c':
+// nMode = MODE_CONCATENATION;
+// break;
+//
+// case 'm':
+// nMode = MODE_MIXING;
+// break;
+//
+// case 'f':
+// nMode = MODE_FLOATMIXING;
+// break;
+//
+// case 'D':
+// DEBUG = true;
+// break;
+//
+// case '?':
+// printUsageAndExit();
+//
+// default:
+// out("AudioConcat.main(): getopt() returned " + c);
+// break;
+// }
+// }
+
+ /*
+ * All remaining arguments are assumed to be filenames of
+ * soundfiles we want to play.
+ */
+// String strFilename = null;
+// for (int i = g.getOptind(); i < args.length; i++)
+// {
+// strFilename = args[i];
+// File soundFile = new File(strFilename);
+//
+// /*
+// * We have to read in the sound file.
+// */
+// AudioInputStream audioInputStream = null;
+// try
+// {
+// audioInputStream = AudioSystem.getAudioInputStream(soundFile);
+// }
+// catch (Exception e)
+// {
+// /*
+// * In case of an exception, we dump the exception
+// * including the stack trace to the console output.
+// * Then, we exit the program.
+// */
+// e.printStackTrace();
+// System.exit(1);
+// }
+// AudioFormat format = audioInputStream.getFormat();
+// /*
+// The first input file determines the audio format. This stream's
+// AudioFormat is stored. All other streams are checked against
+// this format.
+// */
+// if (audioFormat == null)
+// {
+// audioFormat = format;
+// if (DEBUG) { out("AudioConcat.main(): format: " + audioFormat); }
+// }
+// else if ( ! audioFormat.matches(format))
+// {
+// // TODO: try to convert
+// out("AudioConcat.main(): WARNING: AudioFormats don't match");
+// out("AudioConcat.main(): master format: " + audioFormat);
+// out("AudioConcat.main(): this format: " + format);
+// }
+// audioInputStreamList.add(audioInputStream);
+// }
+
+ if (audioFormat == null)
+ {
+ out("No input filenames!");
+ printUsageAndExit();
+ }
+ AudioInputStream audioInputStream = null;
+ switch (nMode)
+ {
+ case MODE_CONCATENATION:
+ audioInputStream = new SequenceAudioInputStream(audioFormat, audioInputStreamList);
+ break;
+
+ case MODE_MIXING:
+ audioInputStream = new MixingAudioInputStream(audioFormat, audioInputStreamList);
+ break;
+
+ case MODE_FLOATMIXING:
+// audioInputStream = new MixingFloatAudioInputStream(audioFormat, audioInputStreamList);
+ break;
+
+ default:
+ out("you have to specify a mode (either -m or -c).");
+ printUsageAndExit();
+ }
+
+ if (strOutputFilename == null)
+ {
+ out("you have to specify an output filename (using -o ).");
+ printUsageAndExit();
+ }
+ File outputFile = new File(strOutputFilename);
+ try
+ {
+ AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, outputFile);
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+
+ if (DEBUG) { out("AudioConcat.main(): before exit"); }
+ System.exit(0);
+ }
+
+
+
+ private static void printUsageAndExit()
+ {
+ out("AudioConcat: usage:");
+ out("\tjava AudioConcat -h");
+ out("\tjava AudioConcat [-D] -c|-m|-f -o ...");
+ System.exit(1);
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java
new file mode 100644
index 0000000..1734e52
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java
@@ -0,0 +1,455 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+
+import javax.sound.sampled.*;
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * @dateTime 19-11-23 下午2:14
+ */
+public class AudioConverter {
+ /** Threshold for float comparisions.
+ If the difference between two floats is smaller than DELTA, they
+ are considered equal.
+ */
+ private static final float DELTA = 1E-9F;
+
+ /** Flag for debugging messages.
+ * If true, some messages are dumped to the console
+ * during operation.
+ */
+ private static boolean DEBUG = false;
+
+ public static void changeWavData(File sourceFile, String targetPath, float fTargetSampleRate, int channel) throws IOException, UnsupportedAudioFileException {
+ AudioFileFormat inputFileFormat = AudioSystem.getAudioFileFormat(sourceFile);
+ AudioFileFormat.Type defaultFileType = inputFileFormat.getType();
+
+ AudioInputStream stream;
+ stream = AudioSystem.getAudioInputStream(sourceFile);
+ AudioFormat format = stream.getFormat();
+ if (DEBUG) out("source format: " + format);
+
+ AudioFormat.Encoding desiredEncoding = format.getEncoding();
+ int nDesiredSampleSizeInBits = format.getSampleSizeInBits();
+ boolean bDesiredBigEndian = format.isBigEndian();
+
+ if (!AudioCommon.isPcm(format.getEncoding()))
+ {
+ if (DEBUG) out("converting to PCM...");
+ AudioFormat.Encoding targetEncoding =
+ (format.getSampleSizeInBits() == 8) ?
+ AudioFormat.Encoding.PCM_UNSIGNED :
+ AudioFormat.Encoding.PCM_SIGNED;
+ stream = convertEncoding(targetEncoding, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+
+ if (nDesiredSampleSizeInBits == AudioSystem.NOT_SPECIFIED)
+ {
+ nDesiredSampleSizeInBits = format.getSampleSizeInBits();
+ }
+ }
+
+ if (stream.getFormat().getChannels() != channel)
+ {
+ if (DEBUG) out("converting channels...");
+ stream = convertChannels(channel, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ boolean bDoConvertSampleSize =
+ (stream.getFormat().getSampleSizeInBits() != nDesiredSampleSizeInBits);
+ boolean bDoConvertEndianess =
+ (stream.getFormat().isBigEndian() != bDesiredBigEndian);
+ if (bDoConvertSampleSize || bDoConvertEndianess)
+ {
+ if (DEBUG) out("converting sample size and endianess...");
+ stream = convertSampleSizeAndEndianess(nDesiredSampleSizeInBits,
+ bDesiredBigEndian, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ if (! equals(stream.getFormat().getSampleRate(), fTargetSampleRate))
+ {
+ if (DEBUG) out("converting sample rate...");
+ stream = convertSampleRate(fTargetSampleRate, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ if (! stream.getFormat().getEncoding().equals(desiredEncoding))
+ {
+ if (DEBUG) out("converting to " + desiredEncoding + "...");
+ stream = convertEncoding(desiredEncoding, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ int nWrittenBytes;
+ nWrittenBytes = AudioSystem.write(stream, defaultFileType, new File(targetPath));
+ if (DEBUG) out("Written bytes: " + nWrittenBytes);
+ }
+
+ public static void main(String[] args)
+ throws UnsupportedAudioFileException, IOException
+ {
+ /** The number of channels the audio data should be converted to.
+ The value is initialized to -1. This is used to represent the
+ condition that conversion of channels is not requested on the
+ command line.
+ */
+ int nDesiredChannels = AudioSystem.NOT_SPECIFIED;
+
+ /** The sample size in bits the audio data should be converted to.
+ */
+ int nDesiredSampleSizeInBits = AudioSystem.NOT_SPECIFIED;
+
+ /** The encoding the audio data should be converted to.
+ */
+ AudioFormat.Encoding desiredEncoding = null;
+
+ /** The sample rate the audio data should be converted to.
+ */
+ float fDesiredSampleRate = AudioSystem.NOT_SPECIFIED;
+
+ /** The file type that should be used to write the audio data.
+ */
+ AudioFileFormat.Type desiredFileType = null;
+
+ /** The endianess the audio data should be converted to.
+ This is only used if bIsEndianessDesired is true.
+ */
+ boolean bDesiredBigEndian = false;
+
+ /** Whether conversion of endianess is desired. This flag is
+ necessary because the boolean variable bDesiredBigEndian
+ has no 'unspecified' value to signal that endianess
+ conversion is not desired.
+ */
+ boolean bIsEndianessDesired = false;
+
+ /*
+ * Parsing of command-line options takes place...
+ */
+// Getopt g = new Getopt("AudioConverter", args, "hlc:s:e:f:t:BLD");
+// int c;
+// while ((c = g.getopt()) != -1)
+// {
+// switch (c)
+// {
+// case 'h':
+// printUsageAndExit();
+//
+// case 'l':
+// // TODO: listSupportedEncodings();
+// AudioCommon.listSupportedTargetTypes();
+// System.exit(0);
+//
+// case 'c':
+// nDesiredChannels = Integer.parseInt(g.getOptarg());
+// break;
+//
+// case 's':
+// nDesiredSampleSizeInBits = Integer.parseInt(g.getOptarg());
+// break;
+//
+// case 'e':
+// String strEncodingName = g.getOptarg();
+// desiredEncoding = new AudioFormat.Encoding(strEncodingName);
+// break;
+//
+// case 'f':
+// fDesiredSampleRate = Float.parseFloat(g.getOptarg());
+// break;
+//
+// case 't':
+// String strExtension = g.getOptarg();
+// desiredFileType = AudioCommon.findTargetType(strExtension);
+// if (desiredFileType == null)
+// {
+// out("Unknown target file type. Check with 'AudioConverter -l'.");
+// System.exit(1);
+// }
+// break;
+//
+// case 'B':
+// bDesiredBigEndian = true;
+// bIsEndianessDesired = true;
+// break;
+//
+// case 'L':
+// bDesiredBigEndian = true;
+// bIsEndianessDesired = true;
+// break;
+//
+// case 'D':
+// DEBUG = true;
+// break;
+//
+// case '?':
+// printUsageAndExit();
+//
+// default:
+// out("getopt() returned " + c);
+// break;
+// }
+// }
+
+ /* We make shure that there are only two more arguments, which
+ we take as the input and output filenames. */
+// if (args.length - g.getOptind() < 2)
+// {
+// printUsageAndExit();
+// }
+
+// File inputFile = new File(args[g.getOptind()]);
+// File outputFile = new File(args[g.getOptind() + 1]);
+
+ File inputFile = new File("/home/yf01/下载/tts/4.wav");
+ File outputFile = new File("/home/yf01/下载/tts/4Change.wav");
+
+ /* As default for the audio file type we use the one of the
+ source file. So we first have to find out about the source
+ file's properties.
+ */
+ AudioFileFormat inputFileFormat = AudioSystem.getAudioFileFormat(inputFile);
+ AudioFileFormat.Type defaultFileType = inputFileFormat.getType();
+
+ /* Here, we are reading the source file.
+ */
+ AudioInputStream stream = null;
+ stream = AudioSystem.getAudioInputStream(inputFile);
+ AudioFormat format = stream.getFormat();
+ if (DEBUG) out("source format: " + format);
+ AudioFormat targetFormat = null;
+
+ /* To ease our job later, we fill the values of the AudioFormat
+ properties not required with the values of the source format.
+ */
+ if (desiredEncoding == null)
+ {
+ desiredEncoding = format.getEncoding();
+ }
+ if (fDesiredSampleRate == AudioSystem.NOT_SPECIFIED)
+ {
+// fDesiredSampleRate = format.getSampleRate();
+ fDesiredSampleRate = 48000;
+ }
+ if (nDesiredSampleSizeInBits == AudioSystem.NOT_SPECIFIED)
+ {
+ nDesiredSampleSizeInBits = format.getSampleSizeInBits();
+ }
+ if (nDesiredChannels == AudioSystem.NOT_SPECIFIED)
+ {
+ nDesiredChannels = format.getChannels();
+ }
+ if (! bIsEndianessDesired)
+ {
+ bDesiredBigEndian = format.isBigEndian();
+ }
+
+ /* Step 1: convert to PCM, if necessary.
+ */
+ if (!AudioCommon.isPcm(format.getEncoding()))
+ {
+ if (DEBUG) out("converting to PCM...");
+ /* The following is a heuristics: normally (but not always),
+ 8 bit audio data are unsigned, while 16 bit data are signed.
+ */
+ AudioFormat.Encoding targetEncoding =
+ (format.getSampleSizeInBits() == 8) ?
+ AudioFormat.Encoding.PCM_UNSIGNED :
+ AudioFormat.Encoding.PCM_SIGNED;
+ stream = convertEncoding(targetEncoding, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+
+ /* Here, we handle a special case: some compressed formats
+ do not state a sample size (but AudioSystem.NOT_SPECIFIED)
+ because its unknown how long
+ the samples are after decoding. If no sample size has been
+ requested with a command line option,
+ In this case, nDesiredSampleSizeInBits still has the value
+ AudioSystem.NOT_SPECIFIED despite the filling with default
+ values above.
+ */
+ if (nDesiredSampleSizeInBits == AudioSystem.NOT_SPECIFIED)
+ {
+ nDesiredSampleSizeInBits = format.getSampleSizeInBits();
+ }
+ }
+
+ /* Step 2: convert number of channels, if necessary.
+ */
+ if (stream.getFormat().getChannels() != nDesiredChannels)
+ {
+ if (DEBUG) out("converting channels...");
+ stream = convertChannels(nDesiredChannels, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ /* Step 3: convert sample size and endianess, if necessary.
+ */
+ boolean bDoConvertSampleSize =
+ (stream.getFormat().getSampleSizeInBits() != nDesiredSampleSizeInBits);
+ boolean bDoConvertEndianess =
+ (stream.getFormat().isBigEndian() != bDesiredBigEndian);
+ if (bDoConvertSampleSize || bDoConvertEndianess)
+ {
+ if (DEBUG) out("converting sample size and endianess...");
+ stream = convertSampleSizeAndEndianess(nDesiredSampleSizeInBits,
+ bDesiredBigEndian, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ /* Step 4: convert sample rate, if necessary.
+ */
+ if (! equals(stream.getFormat().getSampleRate(), fDesiredSampleRate))
+ {
+ if (DEBUG) out("converting sample rate...");
+ stream = convertSampleRate(fDesiredSampleRate, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ /* Step 5: convert to non-PCM encoding, if necessary.
+ */
+ if (! stream.getFormat().getEncoding().equals(desiredEncoding))
+ {
+ if (DEBUG) out("converting to " + desiredEncoding + "...");
+ stream = convertEncoding(desiredEncoding, stream);
+ if (DEBUG) out("stream: " + stream);
+ if (DEBUG) out("format: " + stream.getFormat());
+ }
+
+ /* Since we now know that we are dealing with PCM, we know
+ that the frame rate is the same as the sample rate.
+ */
+// float fTargetFrameRate = fTargetSampleRate;
+
+// /* Here, we are constructing the desired format of the
+// audio data (as the result of the conversion should be).
+// We take over all values besides the sample/frame rate.
+// */
+
+ /* And finally, we are trying to write the converted audio
+ data to a new file.
+ */
+ int nWrittenBytes = 0;
+ AudioFileFormat.Type targetFileType = (desiredFileType != null) ?
+ desiredFileType : defaultFileType;
+ nWrittenBytes = AudioSystem.write(stream, targetFileType, outputFile);
+ if (DEBUG) out("Written bytes: " + nWrittenBytes);
+ }
+
+
+
+ private static AudioInputStream convertEncoding(
+ AudioFormat.Encoding targetEncoding,
+ AudioInputStream sourceStream)
+ {
+ return AudioSystem.getAudioInputStream(targetEncoding,
+ sourceStream);
+ }
+
+
+ private static AudioInputStream convertChannels(
+ int nChannels,
+ AudioInputStream sourceStream)
+ {
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ AudioFormat targetFormat = new AudioFormat(
+ sourceFormat.getEncoding(),
+ sourceFormat.getSampleRate(),
+ sourceFormat.getSampleSizeInBits(),
+ nChannels,
+ calculateFrameSize(nChannels,
+ sourceFormat.getSampleSizeInBits()),
+ sourceFormat.getFrameRate(),
+ sourceFormat.isBigEndian());
+ return AudioSystem.getAudioInputStream(targetFormat,
+ sourceStream);
+ }
+
+
+ private static AudioInputStream convertSampleSizeAndEndianess(
+ int nSampleSizeInBits,
+ boolean bBigEndian,
+ AudioInputStream sourceStream)
+ {
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ AudioFormat targetFormat = new AudioFormat(
+ sourceFormat.getEncoding(),
+ sourceFormat.getSampleRate(),
+ nSampleSizeInBits,
+ sourceFormat.getChannels(),
+ calculateFrameSize(sourceFormat.getChannels(),
+ nSampleSizeInBits),
+ sourceFormat.getFrameRate(),
+ bBigEndian);
+ return AudioSystem.getAudioInputStream(targetFormat,
+ sourceStream);
+ }
+
+
+ private static AudioInputStream convertSampleRate(
+ float fSampleRate,
+ AudioInputStream sourceStream)
+ {
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ AudioFormat targetFormat = new AudioFormat(
+ sourceFormat.getEncoding(),
+ fSampleRate,
+ sourceFormat.getSampleSizeInBits(),
+ sourceFormat.getChannels(),
+ sourceFormat.getFrameSize(),
+ fSampleRate,
+ sourceFormat.isBigEndian());
+ return AudioSystem.getAudioInputStream(targetFormat,
+ sourceStream);
+ }
+
+
+ private static int calculateFrameSize(int nChannels, int nSampleSizeInBits)
+ {
+ return ((nSampleSizeInBits + 7) / 8) * nChannels;
+ }
+
+
+ /** Compares two float values for equality.
+ */
+ private static boolean equals(float f1, float f2)
+ {
+ return (Math.abs(f1 - f2) < DELTA);
+ }
+
+
+
+ private static void printUsageAndExit()
+ {
+ out("AudioConverter: usage:");
+ out("\tjava AudioConverter -h");
+ out("\tjava AudioConverter -l");
+ out("\tjava AudioConverter");
+ out("\t\t[-c ]");
+ out("\t\t[-s ]");
+ out("\t\t[-e ]");
+ out("\t\t[-f ]");
+ out("\t\t[-t ]");
+ out("\t\t[-B|-L] [-D]");
+ out("\t\t ");
+ System.exit(1);
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java
new file mode 100644
index 0000000..2133aba
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java
@@ -0,0 +1,78 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * @dateTime 19-11-23 下午3:47
+ */
+public class AudioDecoder {
+ private static final boolean DEBUG = false;
+
+ public static void main(String[] args)
+ {
+// if (args.length != 2)
+// {
+// printUsageAndExit();
+// }
+// File encodedFile = new File(args[0]);
+// File pcmFile = new File(args[1]);
+
+ File encodedFile = new File("/home/yf01/下载/tts/4.wav");
+ File pcmFile = new File("/home/yf01/下载/tts/4.pcm");
+ AudioInputStream ais = null;
+ try
+ {
+ ais = AudioSystem.getAudioInputStream(encodedFile);
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+
+ if (ais == null)
+ {
+ out("cannot open input file");
+ System.exit(1);
+ }
+ if (DEBUG) { out("AudioDecoder: ais: " + ais); }
+ if (DEBUG) { out("AudioDecoder: ais AudioFormat: " + ais.getFormat()); }
+ if (DEBUG) { out("AudioDecoder: ais length (frames): " + ais.getFrameLength()); }
+ AudioFormat.Encoding targetEncoding = AudioFormat.Encoding.PCM_SIGNED;
+ AudioInputStream pcmAIS = AudioSystem.getAudioInputStream(targetEncoding, ais);
+ if (DEBUG) { out("AudioDecoder: pcmAIS: " + pcmAIS); }
+ if (DEBUG) { out("AudioDecoder: pcmAIS AudioFormat: " + pcmAIS.getFormat()); }
+ if (DEBUG) { out("AudioDecoder: pcmAIS length (frames): " + pcmAIS.getFrameLength()); }
+ AudioFileFormat.Type fileType = AudioFileFormat.Type.AU;
+ int nWrittenBytes = 0;
+ try
+ {
+ nWrittenBytes = AudioSystem.write(pcmAIS, fileType, pcmFile);
+ if (DEBUG) out("AudioDecoder: written (bytes): " + nWrittenBytes);
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+
+
+ private static void printUsageAndExit()
+ {
+ out("AudioDecoder: usage:");
+ out("\tjava AudioDecoder ");
+ System.exit(1);
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java
new file mode 100644
index 0000000..75cf901
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java
@@ -0,0 +1,351 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * @author 苗权威
+ * @dateTime 19-11-25 下午3:08
+ */
+public class MixingAudioInputStream extends AudioInputStream {
+ private static final boolean DEBUG = false;
+
+ private List m_audioInputStreamList;
+
+
+
+ public MixingAudioInputStream(AudioFormat audioFormat, Collection audioInputStreams)
+ {
+ super(new ByteArrayInputStream(new byte[0]),
+ audioFormat,
+ AudioSystem.NOT_SPECIFIED);
+ if (DEBUG) { out("MixingAudioInputStream.(): begin"); }
+ m_audioInputStreamList = new ArrayList(audioInputStreams);
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.(): stream list:");
+ for (int i = 0; i < m_audioInputStreamList.size(); i++)
+ {
+ out(" " + m_audioInputStreamList.get(i));
+ }
+ }
+ if (DEBUG) { out("MixingAudioInputStream.(): end"); }
+ }
+
+
+
+ /**
+ The maximum of the frame length of the input stream is calculated and returned.
+ If at least one of the input streams has length
+ AudioInputStream.NOT_SPECIFIED, this value is returned.
+ */
+ public long getFrameLength()
+ {
+ long lLengthInFrames = 0;
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ long lLength = stream.getFrameLength();
+ if (lLength == AudioSystem.NOT_SPECIFIED)
+ {
+ return AudioSystem.NOT_SPECIFIED;
+ }
+ else
+ {
+ lLengthInFrames = Math.max(lLengthInFrames, lLength);
+ }
+ }
+ return lLengthInFrames;
+ }
+
+
+
+ public int read()
+ throws IOException
+ {
+ if (DEBUG) { out("MixingAudioInputStream.read(): begin"); }
+ int nSample = 0;
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ int nByte = stream.read();
+ if (nByte == -1)
+ {
+ /*
+ The end of this stream has been signaled.
+ We remove the stream from our list.
+ */
+ streamIterator.remove();
+ continue;
+ }
+ else
+ {
+ /*
+ what about signed/unsigned?
+ */
+ nSample += nByte;
+ }
+ }
+ if (DEBUG) { out("MixingAudioInputStream.read(): end"); }
+ return (byte) (nSample & 0xFF);
+ }
+
+
+
+ public int read(byte[] abData, int nOffset, int nLength)
+ throws IOException
+ {
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): begin");
+ out("MixingAudioInputStream.read(byte[], int, int): requested length: " + nLength);
+ }
+ int nChannels = getFormat().getChannels();
+ int nFrameSize = getFormat().getFrameSize();
+ /*
+ This value is in bytes. Note that it is the storage size.
+ It may be four bytes for 24 bit samples.
+ */
+ int nSampleSize = nFrameSize / nChannels;
+ boolean bBigEndian = getFormat().isBigEndian();
+ AudioFormat.Encoding encoding = getFormat().getEncoding();
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): channels: " + nChannels);
+ out("MixingAudioInputStream.read(byte[], int, int): frame size: " + nFrameSize);
+ out("MixingAudioInputStream.read(byte[], int, int): sample size (bytes, storage size): " + nSampleSize);
+ out("MixingAudioInputStream.read(byte[], int, int): big endian: " + bBigEndian);
+ out("MixingAudioInputStream.read(byte[], int, int): encoding: " + encoding);
+ }
+ byte[] abBuffer = new byte[nFrameSize];
+ int[] anMixedSamples = new int[nChannels];
+ for (int nFrameBoundry = 0; nFrameBoundry < nLength; nFrameBoundry += nFrameSize)
+ {
+ if (DEBUG) { out("MixingAudioInputStream.read(byte[], int, int): frame boundry: " + nFrameBoundry); }
+ for (int i = 0; i < nChannels; i++)
+ {
+ anMixedSamples[i] = 0;
+ }
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): AudioInputStream: " + stream);
+ }
+ int nBytesRead = stream.read(abBuffer, 0, nFrameSize);
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): bytes read: " + nBytesRead);
+ }
+ /*
+ TODO: we have to handle incomplete reads.
+ */
+ if (nBytesRead == -1)
+ {
+ /*
+ The end of the current stream has been signaled.
+ We remove it from the list of streams.
+ */
+ streamIterator.remove();
+ continue;
+ }
+ for (int nChannel = 0; nChannel < nChannels; nChannel++)
+ {
+ int nBufferOffset = nChannel * nSampleSize;
+ int nSampleToAdd = 0;
+ if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED))
+ {
+ switch (nSampleSize)
+ {
+ case 1:
+ nSampleToAdd = abBuffer[nBufferOffset];
+ break;
+ case 2:
+// nSampleToAdd = TConversionTool.bytesToInt16(abBuffer, nBufferOffset, bBigEndian);
+ break;
+ case 3:
+// nSampleToAdd = TConversionTool.bytesToInt24(abBuffer, nBufferOffset, bBigEndian);
+ break;
+ case 4:
+// nSampleToAdd = TConversionTool.bytesToInt32(abBuffer, nBufferOffset, bBigEndian);
+ break;
+ }
+ }
+ // TODO: pcm unsigned
+ else if (encoding.equals(AudioFormat.Encoding.ALAW))
+ {
+// nSampleToAdd = TConversionTool.alaw2linear(abBuffer[nBufferOffset]);
+ }
+ else if (encoding.equals(AudioFormat.Encoding.ULAW))
+ {
+// nSampleToAdd = TConversionTool.ulaw2linear(abBuffer[nBufferOffset]);
+ }
+ anMixedSamples[nChannel] += nSampleToAdd;
+ } // loop over channels
+ } // loop over streams
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): starting to write to buffer passed by caller");
+ }
+ for (int nChannel = 0; nChannel < nChannels; nChannel++)
+ {
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): channel: " + nChannel);
+ }
+ int nBufferOffset = nOffset + nFrameBoundry /* * nFrameSize*/ + nChannel * nSampleSize;
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): buffer offset: " + nBufferOffset);
+ }
+ if (encoding.equals(AudioFormat.Encoding.PCM_SIGNED))
+ {
+ switch (nSampleSize)
+ {
+ case 1:
+ abData[nBufferOffset] = (byte) anMixedSamples[nChannel];
+ break;
+ case 2:
+// TConversionTool.intToBytes16(anMixedSamples[nChannel], abData, nBufferOffset, bBigEndian);
+ break;
+ case 3:
+// TConversionTool.intToBytes24(anMixedSamples[nChannel], abData, nBufferOffset, bBigEndian);
+ break;
+ case 4:
+// TConversionTool.intToBytes32(anMixedSamples[nChannel], abData, nBufferOffset, bBigEndian);
+ break;
+ }
+ }
+ // TODO: pcm unsigned
+ else if (encoding.equals(AudioFormat.Encoding.ALAW))
+ {
+// abData[nBufferOffset] = TConversionTool.linear2alaw((short) anMixedSamples[nChannel]);
+ }
+ else if (encoding.equals(AudioFormat.Encoding.ULAW))
+ {
+// abData[nBufferOffset] = TConversionTool.linear2ulaw(anMixedSamples[nChannel]);
+ }
+ } // (final) loop over channels
+ } // loop over frames
+ if (DEBUG)
+ {
+ out("MixingAudioInputStream.read(byte[], int, int): end");
+ }
+ // TODO: return a useful value
+ return nLength;
+ }
+
+
+
+ /**
+ calls skip() on all input streams. There is no way to assure that the number of
+ bytes really skipped is the same for all input streams. Due to that, this
+ method always returns the passed value. In other words: the return value
+ is useless (better ideas appreciated).
+ */
+ public long skip(long lLength)
+ throws IOException
+ {
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ stream.skip(lLength);
+ }
+ return lLength;
+ }
+
+
+
+ /**
+ The minimum of available() of all input stream is calculated and returned.
+ */
+ public int available()
+ throws IOException
+ {
+ int nAvailable = 0;
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ nAvailable = Math.min(nAvailable, stream.available());
+ }
+ return nAvailable;
+ }
+
+
+
+ public void close()
+ throws IOException
+ {
+ // TODO: should we close all streams in the list?
+ }
+
+
+
+ /**
+ Calls mark() on all input streams.
+ */
+ public void mark(int nReadLimit)
+ {
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ stream.mark(nReadLimit);
+ }
+ }
+
+
+ /**
+ Calls reset() on all input streams.
+ */
+ public void reset()
+ throws IOException
+ {
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ stream.reset();
+ }
+ }
+
+
+
+ /**
+ returns true if all input stream return true for markSupported().
+ */
+ public boolean markSupported()
+ {
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ if (! stream.markSupported())
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java
new file mode 100644
index 0000000..677ba3f
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java
@@ -0,0 +1,338 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import javax.sound.sampled.AudioFileFormat;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * @dateTime 19-11-23 下午3:52
+ */
+public class Mp3Encoder {
+ private static boolean DEBUG = false;
+ private static boolean dumpExceptions=false;
+ private static boolean traceConverters=false;
+ private static boolean quiet=false;
+
+ private static final AudioFormat.Encoding MPEG1L3 = new AudioFormat.Encoding("MPEG1L3");
+ private static final AudioFileFormat.Type MP3 = new AudioFileFormat.Type("MP3", "mp3");
+
+ private static AudioInputStream getInStream(String filename)
+ throws IOException {
+ File file = new File(filename);
+ AudioInputStream ais = null;
+ try {
+ ais = AudioSystem.getAudioInputStream(file);
+ } catch (Exception e) {
+ if (dumpExceptions) {
+ e.printStackTrace();
+ } else if (!quiet) {
+ System.out.println("Error: " + e.getMessage());
+ }
+ }
+ if (ais == null) {
+ throw new IOException("Cannot open \"" + filename + "\"");
+ }
+ return ais;
+ }
+
+
+
+ public static String stripExtension(String filename) {
+ int ind = filename.lastIndexOf(".");
+ if (ind == -1
+ || ind == filename.length()
+ || filename.lastIndexOf(File.separator) > ind) {
+ // when dot is at last position,
+ // or a slash is after the dot, there isn't an extension
+ return filename;
+ }
+ return filename.substring(0, ind);
+ }
+
+
+
+ /* first version. Remains here for documentation how to
+ * get a stream with complete description of the target format.
+ */
+ public static AudioInputStream getConvertedStream2(
+ AudioInputStream sourceStream,
+ AudioFormat.Encoding targetEncoding)
+ throws Exception {
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ if (!quiet) {
+ System.out.println("Input format: " + sourceFormat);
+ }
+ // build the output format
+ AudioFormat targetFormat = new AudioFormat(
+ targetEncoding,
+ sourceFormat.getSampleRate(),
+ AudioSystem.NOT_SPECIFIED,
+ sourceFormat.getChannels(),
+ AudioSystem.NOT_SPECIFIED,
+ AudioSystem.NOT_SPECIFIED,
+ false); // endianness doesn't matter
+ // construct a converted stream
+ AudioInputStream targetStream = null;
+ if (!AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
+ if (DEBUG && !quiet) {
+ System.out.println("Direct conversion not possible.");
+ System.out.println("Trying with intermediate PCM format.");
+ }
+ AudioFormat intermediateFormat = new AudioFormat(
+ AudioFormat.Encoding.PCM_SIGNED,
+ sourceFormat.getSampleRate(),
+ 16,
+ sourceFormat.getChannels(),
+ 2 * sourceFormat.getChannels(), // frameSize
+ sourceFormat.getSampleRate(),
+ false);
+ if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
+ // intermediate conversion is supported
+ sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
+ }
+ }
+ targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
+ if (targetStream == null) {
+ throw new Exception("conversion not supported");
+ }
+ if (!quiet) {
+ if (DEBUG) {
+ System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
+ }
+ System.out.println("Output format: " + targetStream.getFormat());
+ }
+ return targetStream;
+ }
+
+
+
+ public static AudioInputStream getConvertedStream(
+ AudioInputStream sourceStream,
+ AudioFormat.Encoding targetEncoding)
+ throws Exception {
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ if (!quiet) {
+ System.out.println("Input format: " + sourceFormat);
+ }
+
+ // construct a converted stream
+ AudioInputStream targetStream = null;
+ if (!AudioSystem.isConversionSupported(targetEncoding, sourceFormat)) {
+ if (DEBUG && !quiet) {
+ System.out.println("Direct conversion not possible.");
+ System.out.println("Trying with intermediate PCM format.");
+ }
+ AudioFormat intermediateFormat = new AudioFormat(
+ AudioFormat.Encoding.PCM_SIGNED,
+ sourceFormat.getSampleRate(),
+ 16,
+ sourceFormat.getChannels(),
+ 2 * sourceFormat.getChannels(), // frameSize
+ sourceFormat.getSampleRate(),
+ false);
+ if (AudioSystem.isConversionSupported(intermediateFormat, sourceFormat)) {
+ // intermediate conversion is supported
+ sourceStream = AudioSystem.getAudioInputStream(intermediateFormat, sourceStream);
+ }
+ }
+ targetStream = AudioSystem.getAudioInputStream(targetEncoding, sourceStream);
+ if (targetStream == null) {
+ throw new Exception("conversion not supported");
+ }
+ if (!quiet) {
+ if (DEBUG) {
+ System.out.println("Got converted AudioInputStream: " + targetStream.getClass().getName());
+ }
+ System.out.println("Output format: " + targetStream.getFormat());
+ }
+ return targetStream;
+ }
+
+
+
+ public static int writeFile(String inFilename) {
+ int writtenBytes = -1;
+ try {
+ AudioFileFormat.Type targetType = MP3;
+ AudioInputStream ais = getInStream(inFilename);
+ ais = getConvertedStream(ais, MPEG1L3);
+
+ // construct the target filename
+ String outFilename = stripExtension(inFilename) + "." + targetType.getExtension();
+
+ // write the file
+ if (!quiet) {
+ System.out.println("Writing " + outFilename + "...");
+ }
+ writtenBytes = AudioSystem.write(ais, targetType, new File(outFilename));
+ if (DEBUG && !quiet) {
+ System.out.println("Effective parameters of output file:");
+ try {
+ String version=System.getProperty("tritonus.lame.encoder.version", "");
+ if (version!="") {
+ System.out.println(" Version = "+version);
+ }
+ System.out.println(" Quality = "+System.getProperty
+ ("tritonus.lame.effective.quality", ""));
+ System.out.println(" Bitrate = "+System.getProperty
+ ("tritonus.lame.effective.bitrate", ""));
+ System.out.println(" Channel Mode = "+System.getProperty
+ ("tritonus.lame.effective.chmode", ""));
+ System.out.println(" VBR mode = "+System.getProperty
+ ("tritonus.lame.effective.vbr", ""));
+ System.out.println(" Sample rate = "+System.getProperty
+ ("tritonus.lame.effective.samplerate", ""));
+ System.out.println(" Encoding = "+System.getProperty
+ ("tritonus.lame.effective.encoding", ""));
+ } catch (Throwable t1) {}
+ }
+ } catch (Throwable t) {
+ if (dumpExceptions) {
+ t.printStackTrace();
+ } else if (!quiet) {
+ System.out.println("Error: " + t.getMessage());
+ }
+ }
+ return writtenBytes;
+ }
+
+
+
+ // returns the first index in args where the files start
+ public static int parseArgs(String[] args) {
+ if (args.length == 0) {
+ usage();
+ }
+ // parse options
+ try {
+ for (int i = 0; i < args.length; i++) {
+ String arg = args[i];
+ if (arg.equals("--help")) {
+ usage();
+ }
+ if (arg.length() > 3 || arg.length() < 2 || !arg.startsWith("-")) {
+ return i;
+ }
+ char cArg = arg.charAt(1);
+ // options without parameter
+ if (cArg == 'v') {
+ DEBUG=true;
+ continue;
+ } else if (cArg == 'e') {
+ dumpExceptions=true;
+ continue;
+ } else if (cArg == 't') {
+// org.tritonus.share.TDebug.TraceAudioConverter=true;
+ continue;
+ } else if (cArg == 's') {
+ quiet=true;
+ continue;
+ } else if (cArg == 'V') {
+ try {
+ System.setProperty("tritonus.lame.vbr", "true");
+ } catch (Throwable t1) {}
+ continue;
+ } else if (cArg == 'h') {
+ usage();
+ }
+ // options with parameter
+ if (args.length < i + 2) {
+ throw new Exception("Missing parameter or unrecognized option "+arg+".");
+ }
+ String param = args[i + 1];
+ i++;
+ switch (cArg) {
+ case 'q':
+ try {
+ System.setProperty("tritonus.lame.quality", param);
+ } catch (Throwable t2) {}
+ break;
+ case 'b':
+ try {
+ System.setProperty("tritonus.lame.bitrate", param);
+ } catch (Throwable t3) {}
+ break;
+ default:
+ throw new Exception("Unrecognized option "+arg+".");
+ }
+ }
+ throw new Exception("No input file(s) are given.");
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ System.exit(1);
+ }
+ return 0; // statement not reached
+ }
+
+
+
+ public static void main(String[] args) {
+ //try {
+ // System.out.println("Librarypath=" + System.getProperty("java.library.path", ""));
+ //} catch (Throwable t) {}
+
+ int firstFileIndex = parseArgs(args);
+ int inputFiles = 0;
+ int success = 0;
+ long totalTime = System.currentTimeMillis();
+ for (int i = firstFileIndex; i < args.length; i++) {
+ long time = System.currentTimeMillis();
+ int bytes = writeFile(args[i]);
+ time = System.currentTimeMillis()-time;
+ inputFiles++;
+ if (bytes >= 0) {
+ if (bytes > 0) {
+ success++;
+ }
+ if (!quiet) {
+ System.out.println("Wrote " + bytes + " bytes in "
+ + (time / 60000) + "m " + ((time/1000) % 60) + "s "
+ + (time % 1000) + "ms ("
+ + (time/1000) + "s).");
+ }
+ }
+ }
+ totalTime = System.currentTimeMillis() - totalTime;
+ if ((DEBUG && quiet) || !quiet) {
+ // this IS displayed in silent DEBUG mode
+ System.out.println("From " + inputFiles + " input file" + (inputFiles == 1 ? "" : "s") + ", "
+ + success + " file" + (success == 1 ? " was" : "s were") + " converted successfully in "
+ + (totalTime / 60000) + "m " + ((totalTime/1000) % 60) + "s ("
+ + (totalTime/1000) + "s).");
+ }
+ System.exit(0);
+ }
+
+
+
+ /** Display a message of how to call this program.
+ */
+ public static void usage() {
+ System.out.println("Mp3Encoder - convert audio files to mp3 (layer III of MPEG 1, MPEG 2 or MPEG 2.5");
+ System.out.println("java Mp3Encoder [...]");
+ System.out.println("The output file(s) will be named like the source file(s) but");
+ System.out.println("with mp3 file extension.");
+ System.out.println("");
+ System.out.println("You need LAME 3.88 or later. Get it from http://sourceforge.net/projects/lame/");
+ System.out.println("");
+ System.out.println(" may be a combination of the following:");
+ System.out.println("-q Quality of output mp3 file. In VBR mode, this affects");
+ System.out.println(" the size of the mp3 file. (Default middle)");
+ System.out.println(" One of: lowest, low, middle, high, highest");
+ System.out.println("-b Bitrate in KBit/s. Useless in VBR mode. (Default 128)");
+ System.out.println(" One of: 32 40 48 56 64 80 96 112 128 160 192 224 256 320 (MPEG1)");
+ System.out.println(" Or: 8 16 24 32 40 48 56 64 80 96 112 128 144 160 (MPEG2 and MPEG2.5");
+ System.out.println("-V VBR (variable bit rate) mode. Slower, but potentially better");
+ System.out.println(" quality. (Default off)");
+ System.out.println("-v Be verbose.");
+ System.out.println("-s Be silent.");
+ System.out.println("-e Debugging: Dump stack trace of exceptions.");
+ System.out.println("-t Debugging: trace execution of converters.");
+ System.out.println("-h | --help Show this message.");
+ System.exit(1);
+ }
+
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java
new file mode 100644
index 0000000..56e3e8e
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java
@@ -0,0 +1,346 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import ai.qiwu.com.tts_service.common.CallPython;
+import ai.qiwu.com.tts_service.service.TTService;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
+import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
+import org.jaudiotagger.audio.mp3.MP3AudioHeader;
+import org.jaudiotagger.audio.mp3.MP3File;
+import org.jaudiotagger.tag.TagException;
+import ws.schild.jave.*;
+
+import javax.sound.sampled.*;
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+/**
+ * @dateTime 19-11-23 下午3:40
+ */
+@Slf4j
+public class SampleRateConverter {
+ /** Flag for debugging messages.
+ * If true, some messages are dumped to the console
+ * during operation.
+ */
+ private static boolean DEBUG = false;
+ public static final String SUFFIX = "TEMP";
+ public static final String SUFFIX_WAV = "TEMP.wav";
+ public static final String SUFFIX_MP3 = "TEMP.mp3";
+ private static final String WAV_SUFFIX = ".wav";
+
+ public static List equalSampleRate(Collection pathList) throws IOException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException {
+ float mouldSampleRate = 0;
+ List changedRateList = new ArrayList<>();
+ boolean first = true;
+ for (String path: pathList) {
+ if (first) {
+ File file = new File(path);
+ mouldSampleRate = getMp3FileSampleRate(file);
+// log.warn("root采样率{}",mouldSampleRate);
+ changedRateList.add(path);
+ first = false;
+ continue;
+ }
+ float num = getMp3FileSampleRate(new File(path));
+// log.warn("{}:采样率:{}", path, num);
+ if (mouldSampleRate != num) {
+// log.warn("{} different",path);
+ int spot = path.lastIndexOf(".");
+ String prefix = path.substring(0, spot);
+ path = prefix+WAV_SUFFIX;
+ if (!new File(path).exists()) {
+ log.error("{}不存在",path);
+ return null;
+ }
+ String tempMp3Path = changeSampleRate(new File(path), prefix, mouldSampleRate);
+ if (StringUtils.isBlank(tempMp3Path)) return null;
+ changedRateList.add(tempMp3Path);
+ } else {
+ changedRateList.add(path);
+ }
+ }
+ return changedRateList;
+ }
+
+ public static List equalWavData(Collection pathList) throws IOException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException {
+ int mouldSampleRate = 0;
+ int channel = 1;
+ List changedRateList = new ArrayList<>();
+ boolean first = true;
+ for (String path: pathList) {
+ if (first) {
+ File file = new File(path);
+ mouldSampleRate = getMp3FileSampleRate(file);
+ channel = getMp3FileChannel(file);
+// log.warn("root采样率{}",mouldSampleRate);
+ changedRateList.add(path);
+ first = false;
+ continue;
+ }
+// log.warn("{}:采样率:{}", path, num);
+ if (mouldSampleRate != getMp3FileSampleRate(new File(path))) {
+// log.warn("{} different",path);
+ int spot = path.lastIndexOf(".");
+ String prefix = path.substring(0, spot);
+ path = prefix+WAV_SUFFIX;
+ String targetWavPath = prefix+SUFFIX_WAV;
+ if (!new File(path).exists()) {
+ log.error("{}不存在",path);
+ return null;
+ }
+ AudioConverter.changeWavData(new File(path), targetWavPath, mouldSampleRate, channel);
+ String tempMp3Path = CallPython.wav2Mp3(targetWavPath, prefix+SUFFIX_MP3);
+ if (tempMp3Path == null) return null;
+ changedRateList.add(tempMp3Path);
+ } else {
+ changedRateList.add(path);
+ }
+ }
+ return changedRateList;
+ }
+
+ public static List equalSampleRateUseFfmepg(Collection pathList) throws EncoderException {
+ int mouldSampleRate = 0;
+ int channel = 1;
+// long bitRate = 0;
+
+ List changedRateList = new ArrayList<>();
+ boolean first = true;
+ int i = -1;
+ List futureList = new ArrayList<>();
+ for (String path: pathList) {
+ i++;
+ final MultimediaObject sourceObject = new MultimediaObject(new File(path));
+ final AudioInfo audioInfo = sourceObject.getInfo().getAudio();
+ if (first) {
+ mouldSampleRate = audioInfo.getSamplingRate();
+ channel = audioInfo.getChannels();
+ changedRateList.add(path);
+ first = false;
+ continue;
+ }
+
+ if (mouldSampleRate != audioInfo.getSamplingRate()) {
+// log.warn("{} different",path);
+ final Integer index = i;
+ final Integer sr = mouldSampleRate;
+ final Integer cl = channel;
+ Future future = TTService.POOL.submit(() -> {
+ try {
+ String tempMp3Path = path.substring(0, path.lastIndexOf("."))+SUFFIX_MP3;
+ ffmepg(sourceObject, audioInfo, tempMp3Path, sr,cl);
+ changedRateList.add(index,tempMp3Path);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ });
+ futureList.add(future);
+ } else {
+ changedRateList.add(i, path);
+ }
+ }
+ for (Future future: futureList) {
+ try {
+ future.get(6, TimeUnit.SECONDS);
+ } catch (InterruptedException | ExecutionException | TimeoutException e) {
+ log.error("ffmpeg error:{}", ExceptionUtils.getStackTrace(e));
+ return null;
+ }
+ }
+ return changedRateList;
+ }
+
+ private static void ffmepg(MultimediaObject sourceObject,AudioInfo audioInfo,String target, int sampleRate, int channel) throws EncoderException {
+ AudioAttributes audio = new AudioAttributes();
+ audio.setCodec("libmp3lame");
+ audio.setBitRate(audioInfo.getBitRate());
+ audio.setChannels(channel);
+ audio.setSamplingRate(sampleRate);
+ EncodingAttributes attrs = new EncodingAttributes();
+ attrs.setFormat("mp3");
+ attrs.setAudioAttributes(audio);
+ Encoder encoder = new Encoder();
+ encoder.encode(sourceObject, new File(target), attrs);
+ }
+
+ private static int getMp3FileSampleRate(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException {
+ MP3File mp3File = new MP3File(file);
+ return mp3File.getMP3AudioHeader().getSampleRateAsNumber();
+ }
+
+ private static int getMp3FileChannel(File file) throws ReadOnlyFileException, TagException, InvalidAudioFrameException, IOException {
+ MP3File mp3File = new MP3File(file);
+ String mode = mp3File.getMP3AudioHeader().getChannels();
+ if (StringUtils.containsIgnoreCase(mode, "Stereo")) return 2;
+ return 1;
+ }
+
+ private static String changeSampleRate(File sourceFile, String targetPath, float fTargetSampleRate) throws IOException, UnsupportedAudioFileException {
+ AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(sourceFile);
+ AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
+
+ AudioInputStream sourceStream;
+ sourceStream = AudioSystem.getAudioInputStream(sourceFile);
+ if (sourceStream == null)
+ {
+ out("cannot open source audio file: " + sourceFile);
+ System.exit(1);
+ }
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ if (DEBUG) { out("source format: " + sourceFormat); }
+
+ AudioFormat.Encoding encoding = sourceFormat.getEncoding();
+ if (! AudioCommon.isPcm(encoding))
+ {
+ out("encoding of source audio data is not PCM; conversion not possible");
+ System.exit(1);
+ }
+
+ float fTargetFrameRate = fTargetSampleRate;
+
+ AudioFormat targetFormat = new AudioFormat(
+ sourceFormat.getEncoding(),
+ fTargetSampleRate,
+ sourceFormat.getSampleSizeInBits(),
+ sourceFormat.getChannels(),
+ sourceFormat.getFrameSize(),
+ fTargetSampleRate,
+ sourceFormat.isBigEndian());
+
+ if (DEBUG) { out("desired target format: " + targetFormat); }
+
+ AudioInputStream targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
+ if (DEBUG) { out("targetStream: " + targetStream); }
+
+ int nWrittenBytes;
+ String wavTargetPath = targetPath+SUFFIX_WAV;
+ nWrittenBytes = AudioSystem.write(targetStream, targetFileType, new File(wavTargetPath));
+ if (DEBUG) { out("Written bytes: " + nWrittenBytes); }
+
+// try {
+// log.warn("{}改变后的采样率:{}",wavTargetPath, AudioSystem.getAudioInputStream(new File(wavTargetPath)).getFormat().getSampleRate());
+// } catch (Exception e) {
+// log.warn("what fuck:{}",e);
+// }
+ return CallPython.wav2Mp3(wavTargetPath, targetPath+SUFFIX_MP3);
+ }
+
+ public static void main(String[] args)
+ throws UnsupportedAudioFileException, IOException
+ {
+// if (args.length == 1)
+// {
+// if (args[0].equals("-h"))
+// {
+// printUsageAndExit();
+// }
+// else
+// {
+// printUsageAndExit();
+// }
+// }
+// else if (args.length != 3)
+// {
+// printUsageAndExit();
+// }
+// float fTargetSampleRate = Float.parseFloat(args[0]);
+// if (DEBUG) { out("target sample rate: " + fTargetSampleRate); }
+// File sourceFile = new File(args[1]);
+// File targetFile = new File(args[2]);
+
+ float fTargetSampleRate = Float.parseFloat("48000");
+ File sourceFile = new File("/home/yf01/下载/us1.wav");
+ File targetFile = new File("/home/yf01/下载/us1change.wav");
+
+ /* We try to use the same audio file type for the target
+ file as the source file. So we first have to find
+ out about the source file's properties.
+ */
+ AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(sourceFile);
+ AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
+
+ /* Here, we are reading the source file.
+ */
+ AudioInputStream sourceStream = null;
+ sourceStream = AudioSystem.getAudioInputStream(sourceFile);
+ if (sourceStream == null)
+ {
+ out("cannot open source audio file: " + sourceFile);
+ System.exit(1);
+ }
+ AudioFormat sourceFormat = sourceStream.getFormat();
+ if (DEBUG) { out("source format: " + sourceFormat); }
+
+ /* Currently, the only known and working sample rate
+ converter for Java Sound requires that the encoding
+ of the source stream is PCM (signed or unsigned).
+ So as a measure of convenience, we check if this
+ holds here.
+ */
+ AudioFormat.Encoding encoding = sourceFormat.getEncoding();
+ if (! AudioCommon.isPcm(encoding))
+ {
+ out("encoding of source audio data is not PCM; conversion not possible");
+ System.exit(1);
+ }
+
+ /* Since we now know that we are dealing with PCM, we know
+ that the frame rate is the same as the sample rate.
+ */
+
+ /* Here, we are constructing the desired format of the
+ audio data (as the result of the conversion should be).
+ We take over all values besides the sample/frame rate.
+ */
+
+ AudioFormat targetFormat = new AudioFormat(
+ sourceFormat.getEncoding(),
+ fTargetSampleRate,
+ sourceFormat.getSampleSizeInBits(),
+ sourceFormat.getChannels(),
+ sourceFormat.getFrameSize(),
+ fTargetSampleRate,
+ sourceFormat.isBigEndian());
+
+ if (DEBUG) { out("desired target format: " + targetFormat); }
+
+ /* Now, the conversion takes place.
+ */
+ AudioInputStream targetStream = AudioSystem.getAudioInputStream(targetFormat, sourceStream);
+ if (DEBUG) { out("targetStream: " + targetStream); }
+
+ /* And finally, we are trying to write the converted audio
+ data to a new file.
+ */
+ int nWrittenBytes = 0;
+ nWrittenBytes = AudioSystem.write(targetStream, targetFileType, targetFile);
+ if (DEBUG) { out("Written bytes: " + nWrittenBytes); }
+ }
+
+
+
+ private static void printUsageAndExit()
+ {
+ out("SampleRateConverter: usage:");
+ out("\tjava SampleRateConverter -h");
+ out("\tjava SampleRateConverter ");
+ System.exit(1);
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java
new file mode 100644
index 0000000..9d2dacc
--- /dev/null
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java
@@ -0,0 +1,240 @@
+package ai.qiwu.com.tts_service.common.sound;
+
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * @dateTime 19-11-25 下午3:06
+ */
+public class SequenceAudioInputStream extends AudioInputStream {
+ private static final boolean DEBUG = true;
+
+ private List m_audioInputStreamList;
+ private int m_nCurrentStream;
+
+
+
+ public SequenceAudioInputStream(AudioFormat audioFormat, Collection audioInputStreams)
+ {
+ super(new ByteArrayInputStream(new byte[0]), audioFormat, AudioSystem.NOT_SPECIFIED);
+ m_audioInputStreamList = new ArrayList(audioInputStreams);
+ m_nCurrentStream = 0;
+ }
+
+
+
+ // TODO: remove
+ private boolean addAudioInputStream(AudioInputStream audioStream)
+ {
+ if (DEBUG)
+ {
+ out("SequenceAudioInputStream.addAudioInputStream(): called.");
+ }
+ // Contract.check(audioStream != null);
+ if (!getFormat().matches(audioStream.getFormat()))
+ {
+ if (DEBUG)
+ {
+ out("SequenceAudioInputStream.addAudioInputStream(): audio formats do not match, trying to convert.");
+ }
+ AudioInputStream asold = audioStream;
+ audioStream = AudioSystem.getAudioInputStream(getFormat(), asold);
+ if (audioStream == null)
+ {
+ out("### SequenceAudioInputStream.addAudioInputStream(): could not convert.");
+ return false;
+ }
+ if (DEBUG)
+ {
+ out(" converted");
+ }
+ }
+ // Contract.check(audioStream != null);
+ synchronized (m_audioInputStreamList)
+ {
+ m_audioInputStreamList.add(audioStream);
+ m_audioInputStreamList.notifyAll();
+ }
+ if (DEBUG)
+ {
+ out("SequenceAudioInputStream.addAudioInputStream(): enqueued " + audioStream);
+ }
+ return true;
+ }
+
+
+
+ private AudioInputStream getCurrentStream()
+ {
+ return (AudioInputStream) m_audioInputStreamList.get(m_nCurrentStream);
+ }
+
+
+
+ private boolean advanceStream()
+ {
+ m_nCurrentStream++;
+ boolean bAnotherStreamAvailable = (m_nCurrentStream < m_audioInputStreamList.size());
+ return bAnotherStreamAvailable;
+ }
+
+
+
+ public long getFrameLength()
+ {
+ long lLengthInFrames = 0;
+ Iterator streamIterator = m_audioInputStreamList.iterator();
+ while (streamIterator.hasNext())
+ {
+ AudioInputStream stream = (AudioInputStream) streamIterator.next();
+ long lLength = stream.getFrameLength();
+ if (lLength == AudioSystem.NOT_SPECIFIED)
+ {
+ return AudioSystem.NOT_SPECIFIED;
+ }
+ else
+ {
+ lLengthInFrames += lLength;
+ }
+ }
+ return lLengthInFrames;
+ }
+
+
+
+ public int read()
+ throws IOException
+ {
+ AudioInputStream stream = getCurrentStream();
+ int nByte = stream.read();
+ if (nByte == -1)
+ {
+ /*
+ The end of the current stream has been signaled.
+ We try to advance to the next stream.
+ */
+ boolean bAnotherStreamAvailable = advanceStream();
+ if (bAnotherStreamAvailable)
+ {
+ /*
+ There is another stream. We recurse into this method
+ to read from it.
+ */
+ return read();
+ }
+ else
+ {
+ /*
+ No more data. We signal EOF.
+ */
+ return -1;
+ }
+ }
+ else
+ {
+ /*
+ The most common case: We return the byte.
+ */
+ return nByte;
+ }
+ }
+
+
+
+ public int read(byte[] abData, int nOffset, int nLength)
+ throws IOException
+ {
+ AudioInputStream stream = getCurrentStream();
+ int nBytesRead = stream.read(abData, nOffset, nLength);
+ if (nBytesRead == -1)
+ {
+ /*
+ The end of the current stream has been signaled.
+ We try to advance to the next stream.
+ */
+ boolean bAnotherStreamAvailable = advanceStream();
+ if (bAnotherStreamAvailable)
+ {
+ /*
+ There is another stream. We recurse into this method
+ to read from it.
+ */
+ return read(abData, nOffset, nLength);
+ }
+ else
+ {
+ /*
+ No more data. We signal EOF.
+ */
+ return -1;
+ }
+ }
+ else
+ {
+ /*
+ The most common case: We return the length.
+ */
+ return nBytesRead;
+ }
+ }
+
+
+
+ public long skip(long lLength)
+ throws IOException
+ {
+ throw new IOException("skip() is not implemented in class SequenceInputStream. Mail if you need this feature.");
+ }
+
+
+
+ public int available()
+ throws IOException
+ {
+ return getCurrentStream().available();
+ }
+
+
+
+ public void close()
+ throws IOException
+ {
+ // TODO: should we close all streams in the list?
+ }
+
+
+
+ public void mark(int nReadLimit)
+ {
+ throw new RuntimeException("mark() is not implemented in class SequenceInputStream. Mail if you need this feature.");
+ }
+
+
+
+ public void reset()
+ throws IOException
+ {
+ throw new IOException("reset() is not implemented in class SequenceInputStream. Mail if you need this feature.");
+ }
+
+
+
+ public boolean markSupported()
+ {
+ return false;
+ }
+
+
+
+ private static void out(String strMessage)
+ {
+ System.out.println(strMessage);
+ }
+}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java
index ad63600..212ab15 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/pojo/TextInfo.java
@@ -23,5 +23,6 @@ public class TextInfo {
private Boolean cache;
private String server;
private String botname;
+ private String botAccount;
private String npcName;
}
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
index 5923b90..b877e4e 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/TTService.java
@@ -47,7 +47,7 @@ public class TTService {
/**
* 线程池,核心线程数cpu数目的两倍,非核心线程存活时间为3s
*/
- private static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE_THREAD_NUM*2,
+ public static final ThreadPoolExecutor POOL = new ThreadPoolExecutor(CORE_THREAD_NUM*2,
1500, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(15),
new ThreadPoolExecutor.CallerRunsPolicy());
@@ -241,13 +241,23 @@ public class TTService {
}
List> futures = new ArrayList<>();
List file_ls = new ArrayList<>();
- String rootFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString();
- String uploadFolder = new StringBuilder(rootFolder).append(Initialize.getUploadedDir()).append(File.separator).toString();
+ String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString();
+ String uploadFolderRoot = new StringBuilder(rootFolderRoot).append(Initialize.getUploadedDir()).append(File.separator).toString();
//String combineFolder = new StringBuilder(rootFolder).append("combine").append(File.separator).toString();
// 第三方语音是否生成,为0则代表不处理该第三方语音
boolean geneThird = request.getGen3rd() == null || request.getGen3rd() != 0;
if (infoList != null && infoList.size() != 0) {
for (TextInfo info : infoList) {
+ String uploadFolder, rootFolder;
+ if (botName.equals(info.getBotAccount()) || StringUtils.isBlank(info.getBotAccount())) {
+ rootFolder = rootFolderRoot;
+ uploadFolder = uploadFolderRoot;
+ } else {
+ rootFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator)
+ .append(info.getBotAccount()).append(File.separator).toString();
+ uploadFolder = new StringBuilder(rootFolder).append(Initialize.getUploadedDir()).append(File.separator).toString();
+ }
+
// person没有值或是不存在则赋予init_person
String person = info.getPerson();
if (StringUtils.isBlank(person)) person = initialize.getInit_person();
@@ -415,8 +425,8 @@ public class TTService {
tmp_name),200), null, 200);
}
} catch (Exception e) {
- log.error("调用python的combine出错:{}", e.toString());
- TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "调用python的combine出错"+e.toString()), null, 555);
+ log.error("合成多个音频文件出错:{}", e.toString());
+ TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "合成多个音频文件出错"), null, 500);
}
}
// 非xiaoai平台的请求,首先将.mp3文件的数据存储在对应的.mp3.b64文件内
diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
index a7b3bfe..14ebbe5 100755
--- a/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
+++ b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java
@@ -1,6 +1,7 @@
package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.TTSUtils;
+import ai.qiwu.com.tts_service.common.sound.SampleRateConverter;
import ai.qiwu.com.tts_service.pojo.TtsLsAudio;
import ai.qiwu.com.tts_service.pojo.TtsLsResponse;
import ai.qiwu.com.tts_service.pojo.TtsLsType;
@@ -10,8 +11,16 @@ import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
+import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
+import org.jaudiotagger.audio.mp3.MP3File;
+import org.jaudiotagger.tag.TagException;
+import javax.sound.sampled.AudioFormat;
+import javax.sound.sampled.AudioInputStream;
+import javax.sound.sampled.AudioSystem;
+import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.*;
import java.math.BigInteger;
import java.net.URLDecoder;
@@ -21,6 +30,8 @@ import java.nio.file.Files;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -253,16 +264,31 @@ public class Test {
return "3";
}
- public static void main(String[] args) throws IOException, ParseException {
+ private static void convert(File input, File outPut) throws IOException, UnsupportedAudioFileException {
+ AudioInputStream stream = AudioSystem.getAudioInputStream(input);
+ AudioFormat format = stream.getFormat();
+ }
+
+ public static void main(String[] args) throws IOException, ParseException, UnsupportedAudioFileException, InvalidAudioFrameException, TagException, ReadOnlyFileException {
Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71");
System.out.println(Arrays.toString(arrr));
Date date = new Date(1572522571234L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :黄河入海流。 当前体力值为"));
- System.out.println(TTSUtils.buildMP3Filename("98"));
- System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :疑是地上霜。 当前体力值为 "));
+ System.out.println(format.format(new Date()));
+ ArrayList list = new ArrayList<>();
+ list.add("/home/yf01/下载/human1.mp3");
+ list.add("/home/yf01/下载/human2.mp3");
+ list.add("/home/yf01/下载/us1.mp3");
+ list.add("/home/yf01/下载/us2.mp3");
+// TTSUtils.combineMp3File(list, "/home/yf01/下载/targetss.mp3");
+
+ try {
+ File[] files = new File("/home/yf01/下载/tts").listFiles((dir, name) -> !name.equals("test"));
+ for (File file: files) System.out.println(file.getName());
+ System.out.println(files.length);
+ } catch (Exception e){}
}
}
diff --git a/tts_service/src/main/resources/deploy.properties b/tts_service/src/main/resources/deploy.properties
new file mode 100755
index 0000000..2a7c312
--- /dev/null
+++ b/tts_service/src/main/resources/deploy.properties
@@ -0,0 +1,16 @@
+server_name=aws-nx2
+server_url=http://aws-nx2.chewrobot.com:9663
+audio_dir=/root/TTS-service/audio
+record_dir=record
+zip_dir=/root/TTS-service/mqwZip
+online_sever=1:http://dev01.centaurstech.com,2:http://dev01.centaurstech.com
+offline_server=http://dev01.centaurstech.com:9001
+#第三方tts标记
+third_party_tts_text =third_party_tts
+
+python_interpreter=/usr/bin/python3
+
+change_sound_path=/root/TTS-service/change_sound.py
+del_cache_callback_url=http://localhost:18082/text/offline/delCache/callback
+record_callback_url=http://localhost:18082/text/offline/upload/callback
+del_record_callback_url=http://localhost:18082/text/offline/delUpload/callback
\ No newline at end of file
diff --git a/tts_service/src/main/resources/static/jave-1.0.2.jar b/tts_service/src/main/resources/static/jave-1.0.2.jar
new file mode 100644
index 0000000..a00a3db
Binary files /dev/null and b/tts_service/src/main/resources/static/jave-1.0.2.jar differ
diff --git a/tts_service/src/main/resources/static/tritonus_share-0.3.6.jar b/tts_service/src/main/resources/static/tritonus_share-0.3.6.jar
new file mode 100644
index 0000000..b9b7ac0
Binary files /dev/null and b/tts_service/src/main/resources/static/tritonus_share-0.3.6.jar differ
diff --git a/tts_service/src/main/resources/tts.properties b/tts_service/src/main/resources/tts.properties
deleted file mode 100755
index 2a7c312..0000000
--- a/tts_service/src/main/resources/tts.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-server_name=aws-nx2
-server_url=http://aws-nx2.chewrobot.com:9663
-audio_dir=/root/TTS-service/audio
-record_dir=record
-zip_dir=/root/TTS-service/mqwZip
-online_sever=1:http://dev01.centaurstech.com,2:http://dev01.centaurstech.com
-offline_server=http://dev01.centaurstech.com:9001
-#第三方tts标记
-third_party_tts_text =third_party_tts
-
-python_interpreter=/usr/bin/python3
-
-change_sound_path=/root/TTS-service/change_sound.py
-del_cache_callback_url=http://localhost:18082/text/offline/delCache/callback
-record_callback_url=http://localhost:18082/text/offline/upload/callback
-del_record_callback_url=http://localhost:18082/text/offline/delUpload/callback
\ No newline at end of file
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
index 419bd7d..9672c72 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/controller/XiaoDuHomeController.java
@@ -45,6 +45,16 @@ public class XiaoDuHomeController {
// return xiaoAiService.getResponse(request);
}
+ @RequestMapping("/xiaoai/child")
+ public XiaoAiResponse xiaoaiChild(@RequestBody XiaoAiRequest request) {
+ //log.info("请求:"+request);
+ request.setType(1);
+ XiaoAiResponse response = xiaoAiService.getResponse(request);
+// log.info("响应:"+response);
+ return response;
+// return xiaoAiService.getResponse(request);
+ }
+
@RequestMapping("/xiaoduhome/chat")
public String chat() {
try {
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
index 7e45704..56363bd 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/RequestTerminal.java
@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.math.NumberUtils;
import java.io.IOException;
import java.util.HashMap;
@@ -24,7 +25,7 @@ public class RequestTerminal {
* @return mp3链接及文字描述
* @throws IOException
*/
- public static QiWuResponse requestTerminate(String userId, String userWord) throws IOException {
+ public static QiWuResponse requestTerminate(String userId, String userWord, Integer type) throws IOException {
QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId);
// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
@@ -33,7 +34,8 @@ public class RequestTerminal {
//log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8");
- headers.put("App-Channel-Id", "jiaoyou-audio-test");
+ if (NumberUtils.INTEGER_ONE.equals(type)) headers.put("App-Channel-Id", "jiaoyou-audio-child-test");
+ else headers.put("App-Channel-Id", "jiaoyou-audio-test");
String resStr;
if (userId.equals(XiaoAiService.deviceId)) {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
index c078946..86e232b 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/common/XiaoAiConstants.java
@@ -22,7 +22,9 @@ public interface XiaoAiConstants {
interface TTS {
String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您";
+ String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
+ String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_WORD = "退出";
String USER_IDLE = "小悟在等你的回复";
String ANOTHER_USER_IDLE = "再不回复我,那我可退出喽";
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/XiaoAiRequest.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/XiaoAiRequest.java
index 6eed130..f6a973a 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/XiaoAiRequest.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/model/request/XiaoAiRequest.java
@@ -3,6 +3,7 @@ package ai.qiwu.com.xiaoduhome.xiaoai.model.request;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.context.Context;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest.Request;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.session.Session;
+import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@@ -14,10 +15,13 @@ import lombok.ToString;
@Getter
@Setter
@ToString
+@JsonIgnoreProperties(ignoreUnknown = true)
public class XiaoAiRequest {
private String version;
private String query;
private Session session;
private Context context;
private Request request;
+
+ private Integer type; // 1 为jiaoyou-audio-child-test
}
diff --git a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
index 6d839e5..177c197 100755
--- a/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
+++ b/xiaoduhome/src/main/java/ai/qiwu/com/xiaoduhome/xiaoai/service/XiaoAiService.java
@@ -64,7 +64,7 @@ public class XiaoAiService {
switch (type) {
case 0 : return dealWithLaunchRequest(request);
case 1 : return dealWithIntentRequest(request, userId);
- case 2 : return dealWithEndRequest(userId);
+ case 2 : return dealWithEndRequest(userId, request.getType());
default: return buildTextResponse(SORRY_REPEAT);
}
}
@@ -179,6 +179,7 @@ public class XiaoAiService {
// }
LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.remove(getUserId(request));
+ if (NumberUtils.INTEGER_ONE.equals(request.getType())) return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD_CHILD);
return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD);
}
@@ -236,7 +237,7 @@ public class XiaoAiService {
// XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response;
try {
- Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery()));
+ Future future = DplbotServiceUtil.getPool().submit(new Task(userId, request.getQuery(), request.getType()));
future.get(2100, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString());
@@ -257,16 +258,17 @@ public class XiaoAiService {
* @param userId 用户id
* @return 返回信息
*/
- private XiaoAiResponse dealWithEndRequest(String userId) {
+ private XiaoAiResponse dealWithEndRequest(String userId, Integer type) {
DplbotServiceUtil.getPool().submit(() -> {
try {
- RequestTerminal.requestTerminate(userId, XiaoAiConstants.TTS.END_WORD);
+ RequestTerminal.requestTerminate(userId, XiaoAiConstants.TTS.END_WORD, type);
} catch (Exception e) {
log.error("向终端发出的退出请求失败:{}", e.toString());
}
});
LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.remove(userId);
+ if (NumberUtils.INTEGER_ONE.equals(type)) return buildTextResponse(XiaoAiConstants.TTS.END_BYE_CHILD);
return buildTextResponse(XiaoAiConstants.TTS.END_BYE);
}
@@ -294,12 +296,14 @@ public class XiaoAiService {
* 任务封装类
*/
class Task implements Runnable {
- private String userId;
- private String userWord;
+ private final String userId;
+ private final String userWord;
+ private final Integer type;
- Task(String userId, String userWord) {
+ Task(String userId, String userWord, Integer type) {
this.userId = userId;
this.userWord = userWord;
+ this.type = type;
}
@Override
@@ -312,7 +316,7 @@ public class XiaoAiService {
log.info("小爱,用户说的话:{}", userWord);
QiWuResponse response;
try {
- response = RequestTerminal.requestTerminate(userId, userWord);
+ response = RequestTerminal.requestTerminate(userId, userWord, type);
} catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestTerminateFail(e.toString());
diff --git a/xiaoduhome/src/main/resources/templates/index.html b/xiaoduhome/src/main/resources/templates/index.html
index f3badf8..b1b8a97 100644
--- a/xiaoduhome/src/main/resources/templates/index.html
+++ b/xiaoduhome/src/main/resources/templates/index.html
@@ -12,7 +12,7 @@
-
+