Commit f64a2e4c by 苗权威

11.28

parent f8b3597c
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
<module name="open" options="-parameters" /> <module name="open" options="-parameters" />
<module name="rokid" options="-parameters" /> <module name="rokid" options="-parameters" />
<module name="ruoqi" options="-parameters" /> <module name="ruoqi" options="-parameters" />
<module name="spirit" options="-parameters -extdirs /usr/local/intellij/workplace/smartbox/spirit/src/main/resources/lib" /> <module name="spirit" options="-parameters -extdirs $PROJECT_DIR$/spirit/src/main/resources/lib" />
<module name="third_party_load" options="-parameters" /> <module name="third_party_load" options="-parameters" />
<module name="tts_offline" options="-parameters" /> <module name="tts_offline" options="-parameters" />
<module name="tts_service" options="-parameters" /> <module name="tts_service" options="-parameters" />
......
...@@ -104,6 +104,38 @@ ...@@ -104,6 +104,38 @@
<artifactId>commons-csv</artifactId> <artifactId>commons-csv</artifactId>
<version>1.7</version> <version>1.7</version>
</dependency> </dependency>
<!--&lt;!&ndash; https://mvnrepository.com/artifact/gnu.getopt/java-getopt &ndash;&gt;-->
<!--<dependency>-->
<!--<groupId>gnu.getopt</groupId>-->
<!--<artifactId>java-getopt</artifactId>-->
<!--<version>1.0.13</version>-->
<!--</dependency>-->
<!-- https://mvnrepository.com/artifact/ws.schild/jave-all-deps -->
<dependency>
<groupId>ws.schild</groupId>
<artifactId>jave-all-deps</artifactId>
<version>2.7.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org/jaudiotagger -->
<dependency>
<groupId>org</groupId>
<artifactId>jaudiotagger</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>com.jave</groupId>
<artifactId>jave</artifactId>
<version>1.0.2</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/static/jave-1.0.2.jar</systemPath>
</dependency>
<!--<dependency>-->
<!--<groupId>org.tritonus.share</groupId>-->
<!--<artifactId>tritonus</artifactId>-->
<!--<version>0.3.6</version>-->
<!--<scope>system</scope>-->
<!--<systemPath>${project.basedir}/src/main/resources/static/tritonus_share-0.3.6.jar</systemPath>-->
<!--</dependency>-->
</dependencies> </dependencies>
<build> <build>
...@@ -112,6 +144,9 @@ ...@@ -112,6 +144,9 @@
<plugin> <plugin>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<includeSystemScope>true</includeSystemScope>
</configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
......
...@@ -43,6 +43,13 @@ public class CallPython { ...@@ -43,6 +43,13 @@ public class CallPython {
return result; 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 * 调用python来合成mp3
* @param wav_filename wav文件地址 * @param wav_filename wav文件地址
...@@ -67,7 +74,7 @@ public class CallPython { ...@@ -67,7 +74,7 @@ public class CallPython {
*/ */
public static void getPythonInterpreter() { public static void getPythonInterpreter() {
String interpreter = processUtil("pipenv run which python"); String interpreter = processUtil("pipenv run which python");
log.info("获取的python解释器位置:{}", interpreter); log.warn("获取的python解释器位置:{}", interpreter);
if (StringUtils.isNotBlank(interpreter)) INTERPRETER = interpreter; if (StringUtils.isNotBlank(interpreter)) INTERPRETER = interpreter;
} }
......
...@@ -20,7 +20,7 @@ public class Config { ...@@ -20,7 +20,7 @@ public class Config {
private static Properties properties; private static Properties properties;
static { static {
// String filename = "tts.properties"; // String filename = "deploy.properties";
// String filename = "ttsDidi.properties"; // String filename = "ttsDidi.properties";
// String filename = "ttsTest.properties"; // String filename = "ttsTest.properties";
String filename = "deploy.properties"; String filename = "deploy.properties";
...@@ -29,7 +29,7 @@ public class Config { ...@@ -29,7 +29,7 @@ public class Config {
// properties.load(new InputStreamReader(Objects.requireNonNull(Config.class.getClassLoader().getResourceAsStream(filename)), StandardCharsets.UTF_8)); // properties.load(new InputStreamReader(Objects.requireNonNull(Config.class.getClassLoader().getResourceAsStream(filename)), StandardCharsets.UTF_8));
String path = System.getProperty("java.class.path"); String path = System.getProperty("java.class.path");
path = path.substring(0, path.lastIndexOf(File.separator)+1) + filename; 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)); properties.load(new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
} catch (Exception e) { } catch (Exception e) {
log.error("获取配置文件对象出错:{}", e.toString()); log.error("获取配置文件对象出错:{}", e.toString());
......
package ai.qiwu.com.tts_service.common; 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.pojo.TTSRequest;
import ai.qiwu.com.tts_service.service.Initialize; import ai.qiwu.com.tts_service.service.Initialize;
import ai.qiwu.com.tts_service.service.TTService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils; import org.springframework.util.DigestUtils;
import javax.sound.sampled.AudioFileFormat; import javax.sound.sampled.AudioFileFormat;
...@@ -482,9 +485,18 @@ public class TTSUtils { ...@@ -482,9 +485,18 @@ public class TTSUtils {
*/ */
public static void combineMp3File(Collection<String> filePathList, String targetFilepath) public static void combineMp3File(Collection<String> filePathList, String targetFilepath)
throws IOException { throws IOException {
try {
// List<String> filePaths = SampleRateConverter.equalSampleRate(filePathList);
// List<String> filePaths = SampleRateConverter.equalWavData(filePathList);
List<String> 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)))){ try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(targetFilepath)))){
AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>(); AudioEnumeration<InputStream> audioEnumeration = new AudioEnumeration<>();
for (String filepath : filePathList) { for (String filepath : filePathList) {
// log.warn(filepath);
if (filepath.equals(Initialize.getThirdParty())) { if (filepath.equals(Initialize.getThirdParty())) {
continue; continue;
} }
...@@ -499,6 +511,16 @@ public class TTSUtils { ...@@ -499,6 +511,16 @@ public class TTSUtils {
outputStream.flush(); outputStream.flush();
sequenceInputStream.close(); sequenceInputStream.close();
} }
final List<String> 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);
}
}
});
} }
/** /**
......
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);
}
}
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<String> 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 <filename>).");
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 <outputfile> <inputfile> ...");
System.exit(1);
}
private static void out(String strMessage)
{
System.out.println(strMessage);
}
}
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 <encodedfile> <pcmfile>");
System.exit(1);
}
private static void out(String strMessage)
{
System.out.println(strMessage);
}
}
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);
}
}
...@@ -23,5 +23,6 @@ public class TextInfo { ...@@ -23,5 +23,6 @@ public class TextInfo {
private Boolean cache; private Boolean cache;
private String server; private String server;
private String botname; private String botname;
private String botAccount;
private String npcName; private String npcName;
} }
...@@ -47,7 +47,7 @@ public class TTService { ...@@ -47,7 +47,7 @@ public class TTService {
/** /**
* 线程池,核心线程数cpu数目的两倍,非核心线程存活时间为3s * 线程池,核心线程数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), 1500, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<>(15),
new ThreadPoolExecutor.CallerRunsPolicy()); new ThreadPoolExecutor.CallerRunsPolicy());
...@@ -241,13 +241,23 @@ public class TTService { ...@@ -241,13 +241,23 @@ public class TTService {
} }
List<Future<ResponseCodeWithData>> futures = new ArrayList<>(); List<Future<ResponseCodeWithData>> futures = new ArrayList<>();
List<String> file_ls = new ArrayList<>(); List<String> file_ls = new ArrayList<>();
String rootFolder = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString(); String rootFolderRoot = new StringBuilder(Initialize.getAudioDir()).append(File.separator).append(botName).append(File.separator).toString();
String uploadFolder = new StringBuilder(rootFolder).append(Initialize.getUploadedDir()).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(); //String combineFolder = new StringBuilder(rootFolder).append("combine").append(File.separator).toString();
// 第三方语音是否生成,为0则代表不处理该第三方语音 // 第三方语音是否生成,为0则代表不处理该第三方语音
boolean geneThird = request.getGen3rd() == null || request.getGen3rd() != 0; boolean geneThird = request.getGen3rd() == null || request.getGen3rd() != 0;
if (infoList != null && infoList.size() != 0) { if (infoList != null && infoList.size() != 0) {
for (TextInfo info : infoList) { for (TextInfo info : infoList) {
String 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 // person没有值或是不存在则赋予init_person
String person = info.getPerson(); String person = info.getPerson();
if (StringUtils.isBlank(person)) person = initialize.getInit_person(); if (StringUtils.isBlank(person)) person = initialize.getInit_person();
...@@ -415,8 +425,8 @@ public class TTService { ...@@ -415,8 +425,8 @@ public class TTService {
tmp_name),200), null, 200); tmp_name),200), null, 200);
} }
} catch (Exception e) { } catch (Exception e) {
log.error("调用python的combine出错:{}", e.toString()); log.error("合成多个音频文件出错:{}", e.toString());
TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "调用python的combine出错"+e.toString()), null, 555); TTServiceUtil.buildTTS_lsResponse(response, new TTSResponse(555, "合成多个音频文件出错"), null, 500);
} }
} }
// 非xiaoai平台的请求,首先将.mp3文件的数据存储在对应的.mp3.b64文件内 // 非xiaoai平台的请求,首先将.mp3文件的数据存储在对应的.mp3.b64文件内
......
package ai.qiwu.com.tts_service.service; package ai.qiwu.com.tts_service.service;
import ai.qiwu.com.tts_service.common.TTSUtils; 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.TtsLsAudio;
import ai.qiwu.com.tts_service.pojo.TtsLsResponse; import ai.qiwu.com.tts_service.pojo.TtsLsResponse;
import ai.qiwu.com.tts_service.pojo.TtsLsType; import ai.qiwu.com.tts_service.pojo.TtsLsType;
...@@ -10,8 +11,16 @@ import com.csvreader.CsvReader; ...@@ -10,8 +11,16 @@ import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils; 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.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.URLDecoder; import java.net.URLDecoder;
...@@ -21,6 +30,8 @@ import java.nio.file.Files; ...@@ -21,6 +30,8 @@ import java.nio.file.Files;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
...@@ -253,16 +264,31 @@ public class Test { ...@@ -253,16 +264,31 @@ public class Test {
return "3"; 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()); Pattern pattern = Pattern.compile(TTSUtils.getAbRegex());
String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71"); String[] arrr = pattern.split("回答错误,正确答案为 :风吹草地见牛羊。 当前体力值为 \uD83C\uDD7097\uD83C\uDD71");
System.out.println(Arrays.toString(arrr)); System.out.println(Arrays.toString(arrr));
Date date = new Date(1572522571234L); Date date = new Date(1572522571234L);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :黄河入海流。 当前体力值为")); System.out.println(format.format(new Date()));
System.out.println(TTSUtils.buildMP3Filename("98")); ArrayList<String> list = new ArrayList<>();
System.out.println(TTSUtils.buildMP3Filename("回答错误,正确答案为 :疑是地上霜。 当前体力值为 ")); 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){}
} }
} }
...@@ -45,6 +45,16 @@ public class XiaoDuHomeController { ...@@ -45,6 +45,16 @@ public class XiaoDuHomeController {
// return xiaoAiService.getResponse(request); // 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") @RequestMapping("/xiaoduhome/chat")
public String chat() { public String chat() {
try { try {
......
...@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse; ...@@ -6,6 +6,7 @@ import ai.qiwu.com.xiaoduhome.xiaoai.model.QiWuResponse;
import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService; import ai.qiwu.com.xiaoduhome.xiaoai.service.XiaoAiService;
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
...@@ -24,7 +25,7 @@ public class RequestTerminal { ...@@ -24,7 +25,7 @@ public class RequestTerminal {
* @return mp3链接及文字描述 * @return mp3链接及文字描述
* @throws IOException * @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(); QiWuRequest requestPojo = new QiWuRequest();
requestPojo.setUid(userId); requestPojo.setUid(userId);
// requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME); // requestPojo.setAccess(XiaoAiConstants.DEVICE_NAME);
...@@ -33,7 +34,8 @@ public class RequestTerminal { ...@@ -33,7 +34,8 @@ public class RequestTerminal {
//log.info("向终端发出请求的参数信息:{}", requestJsonStr); //log.info("向终端发出请求的参数信息:{}", requestJsonStr);
HashMap<String, String> headers = new HashMap<>(); HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json;charset=utf-8"); 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; String resStr;
if (userId.equals(XiaoAiService.deviceId)) { if (userId.equals(XiaoAiService.deviceId)) {
resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers); resStr = OkHttp3Utils.doPostJsonStr(XiaoAiConstants.QI_WU_TERMINATE_DIDI, requestJsonStr, headers);
......
...@@ -22,7 +22,9 @@ public interface XiaoAiConstants { ...@@ -22,7 +22,9 @@ public interface XiaoAiConstants {
interface TTS { interface TTS {
String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您"; String WELCOME_WORD = "欢迎来到交游天下,海量的作品在这等您";
String WELCOME_WORD_CHILD = "小朋友你好,欢迎来到智能故事";
String END_BYE = "我们的作品库在不断扩充,欢迎再来玩"; String END_BYE = "我们的作品库在不断扩充,欢迎再来玩";
String END_BYE_CHILD = "再见啦小朋友,记得下次再来玩哦";
String END_WORD = "退出"; String END_WORD = "退出";
String USER_IDLE = "小悟在等你的回复"; String USER_IDLE = "小悟在等你的回复";
String ANOTHER_USER_IDLE = "再不回复我,那我可退出喽"; String ANOTHER_USER_IDLE = "再不回复我,那我可退出喽";
......
...@@ -3,6 +3,7 @@ package ai.qiwu.com.xiaoduhome.xiaoai.model.request; ...@@ -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.context.Context;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest.Request; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.innerRequest.Request;
import ai.qiwu.com.xiaoduhome.xiaoai.model.request.session.Session; import ai.qiwu.com.xiaoduhome.xiaoai.model.request.session.Session;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
...@@ -14,10 +15,13 @@ import lombok.ToString; ...@@ -14,10 +15,13 @@ import lombok.ToString;
@Getter @Getter
@Setter @Setter
@ToString @ToString
@JsonIgnoreProperties(ignoreUnknown = true)
public class XiaoAiRequest { public class XiaoAiRequest {
private String version; private String version;
private String query; private String query;
private Session session; private Session session;
private Context context; private Context context;
private Request request; private Request request;
private Integer type; // 1 为jiaoyou-audio-child-test
} }
...@@ -64,7 +64,7 @@ public class XiaoAiService { ...@@ -64,7 +64,7 @@ public class XiaoAiService {
switch (type) { switch (type) {
case 0 : return dealWithLaunchRequest(request); case 0 : return dealWithLaunchRequest(request);
case 1 : return dealWithIntentRequest(request, userId); case 1 : return dealWithIntentRequest(request, userId);
case 2 : return dealWithEndRequest(userId); case 2 : return dealWithEndRequest(userId, request.getType());
default: return buildTextResponse(SORRY_REPEAT); default: return buildTextResponse(SORRY_REPEAT);
} }
} }
...@@ -179,6 +179,7 @@ public class XiaoAiService { ...@@ -179,6 +179,7 @@ public class XiaoAiService {
// } // }
LAST_OUTTIME_RESULT.remove(getUserId(request)); LAST_OUTTIME_RESULT.remove(getUserId(request));
LAST_OUTTIME_MARK.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); return buildTextResponse(XiaoAiConstants.TTS.WELCOME_WORD);
} }
...@@ -236,7 +237,7 @@ public class XiaoAiService { ...@@ -236,7 +237,7 @@ public class XiaoAiService {
// XiaoAiResponse response = getLastResult(userId); // XiaoAiResponse response = getLastResult(userId);
// if (response != null) return response; // if (response != null) return response;
try { 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); future.get(2100, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) { } catch (InterruptedException | ExecutionException e) {
log.error("获取任务执行结果出错:{}", e.toString()); log.error("获取任务执行结果出错:{}", e.toString());
...@@ -257,16 +258,17 @@ public class XiaoAiService { ...@@ -257,16 +258,17 @@ public class XiaoAiService {
* @param userId 用户id * @param userId 用户id
* @return 返回信息 * @return 返回信息
*/ */
private XiaoAiResponse dealWithEndRequest(String userId) { private XiaoAiResponse dealWithEndRequest(String userId, Integer type) {
DplbotServiceUtil.getPool().submit(() -> { DplbotServiceUtil.getPool().submit(() -> {
try { try {
RequestTerminal.requestTerminate(userId, XiaoAiConstants.TTS.END_WORD); RequestTerminal.requestTerminate(userId, XiaoAiConstants.TTS.END_WORD, type);
} catch (Exception e) { } catch (Exception e) {
log.error("向终端发出的退出请求失败:{}", e.toString()); log.error("向终端发出的退出请求失败:{}", e.toString());
} }
}); });
LAST_OUTTIME_MARK.remove(userId); LAST_OUTTIME_MARK.remove(userId);
LAST_OUTTIME_RESULT.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); return buildTextResponse(XiaoAiConstants.TTS.END_BYE);
} }
...@@ -294,12 +296,14 @@ public class XiaoAiService { ...@@ -294,12 +296,14 @@ public class XiaoAiService {
* 任务封装类 * 任务封装类
*/ */
class Task implements Runnable { class Task implements Runnable {
private String userId; private final String userId;
private String userWord; private final String userWord;
private final Integer type;
Task(String userId, String userWord) { Task(String userId, String userWord, Integer type) {
this.userId = userId; this.userId = userId;
this.userWord = userWord; this.userWord = userWord;
this.type = type;
} }
@Override @Override
...@@ -312,7 +316,7 @@ public class XiaoAiService { ...@@ -312,7 +316,7 @@ public class XiaoAiService {
log.info("小爱,用户说的话:{}", userWord); log.info("小爱,用户说的话:{}", userWord);
QiWuResponse response; QiWuResponse response;
try { try {
response = RequestTerminal.requestTerminate(userId, userWord); response = RequestTerminal.requestTerminate(userId, userWord, type);
} catch (Exception e) { } catch (Exception e) {
log.error("向终端发出的请求信息失败:{}", e.toString()); log.error("向终端发出的请求信息失败:{}", e.toString());
throw new RequestTerminateFail(e.toString()); throw new RequestTerminateFail(e.toString());
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
<button type="button" class="layui-btn button " id="one">小度1号 (gz4)</button> <button type="button" class="layui-btn button " id="one">小度1号 (gz4)</button>
<button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button> <button type="button" class="layui-btn button " id="four">小度2号 (gz3)</button>
<button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button> <button type="button" class="layui-btn button " id="tow">小爱1号(gz3)</button>
<button type="button" class="layui-btn button " id="therr">小爱2号(gz3)</button> <button type="button" class="layui-btn button " id="therr">小爱2号(gz4)</button>
</div> </div>
</body> </body>
<style> <style>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment