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 c2a7903..3c823f2 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,16 +1,10 @@ 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.RandomStringUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.springframework.data.redis.core.StringRedisTemplate; -import org.springframework.util.CollectionUtils; import org.springframework.util.DigestUtils; import javax.sound.sampled.AudioFileFormat; @@ -18,7 +12,6 @@ import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.UnsupportedAudioFileException; import java.io.*; -import java.nio.channels.FileLock; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.*; diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavFileHeader.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavFileHeader.java deleted file mode 100755 index 52245a7..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavFileHeader.java +++ /dev/null @@ -1,60 +0,0 @@ -package ai.qiwu.com.tts_service.common.pcm; - -/** - * 构建wav文件的头数据 - * @author 苗权威 - * @dateTime 19-8-14 下午2:20 - */ -public class WavFileHeader { - /** - * RIFF数据块 - */ - final String riffChunkId = "RIFF"; - int riffChunkSize; - final String riffType = "WAVE"; - - /** - * FORMAT 数据块 - */ - final String formatChunkId = "fmt "; - final int formatChunkSize = 16; - final short audioFormat = 1; - short channels; - int sampleRate; - int byteRate; - short blockAlign; - short sampleBits; - - /** - * FORMAT 数据块 - */ - final String dataChunkId = "data"; - int dataChunkSize; - - WavFileHeader(int totalAudioLen, int sampleRate, short channels, short sampleBits) { - this.riffChunkSize = totalAudioLen; - this.channels = channels; - this.sampleRate = sampleRate; - this.byteRate = sampleRate * sampleBits / 8 * channels; - this.blockAlign = (short) (channels * sampleBits / 8); - this.sampleBits = sampleBits; - this.dataChunkSize = totalAudioLen - 44; - } - - public byte[] getHeader() { - byte[] result; - result = ByteUtils.merger(ByteUtils.toBytes(riffChunkId), ByteUtils.toBytes(riffChunkSize)); - result = ByteUtils.merger(result, ByteUtils.toBytes(riffType)); - result = ByteUtils.merger(result, ByteUtils.toBytes(formatChunkId)); - result = ByteUtils.merger(result, ByteUtils.toBytes(formatChunkSize)); - result = ByteUtils.merger(result, ByteUtils.toBytes(audioFormat)); - result = ByteUtils.merger(result, ByteUtils.toBytes(channels)); - result = ByteUtils.merger(result, ByteUtils.toBytes(sampleRate)); - result = ByteUtils.merger(result, ByteUtils.toBytes(byteRate)); - result = ByteUtils.merger(result, ByteUtils.toBytes(blockAlign)); - result = ByteUtils.merger(result, ByteUtils.toBytes(sampleBits)); - result = ByteUtils.merger(result, ByteUtils.toBytes(dataChunkId)); - result = ByteUtils.merger(result, ByteUtils.toBytes(dataChunkSize)); - return result; - } -} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavHeader.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavHeader.java deleted file mode 100755 index 4021943..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavHeader.java +++ /dev/null @@ -1,88 +0,0 @@ -package ai.qiwu.com.tts_service.common.pcm; - -import lombok.Setter; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -/** - * 获取wav文件的头数据 - * @author 苗权威 - * @dateTime 19-8-14 下午12:16 - */ -@Setter -public class WavHeader { - private final char fileID[] = {'R', 'I', 'F', 'F'}; - private int fileLength; - private char wavTag[] = {'W', 'A', 'V', 'E'};; - private char FmtHdrID[] = {'f', 'm', 't', ' '}; - private int FmtHdrLeth; - private short FormatTag; - private short Channels; - private int SamplesPerSec; - private int AvgBytesPerSec; - private short BlockAlign; - private short BitsPerSample; - private char DataHdrID[] = {'d','a','t','a'}; - private int DataHdrLeth; - - public WavHeader() { - } - - public WavHeader(int fileLength, int fmtHdrLeth, short formatTag, short channels, - int samplesPerSec, int avgBytesPerSec, short blockAlign, short bitsPerSample, int dataHdrLeth) { - this.fileLength = fileLength; - FmtHdrLeth = fmtHdrLeth; - FormatTag = formatTag; - Channels = channels; - SamplesPerSec = samplesPerSec; - AvgBytesPerSec = avgBytesPerSec; - BlockAlign = blockAlign; - BitsPerSample = bitsPerSample; - DataHdrLeth = dataHdrLeth; - } - - public byte[] getHeader() throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - WriteChar(bos, fileID); - WriteInt(bos, fileLength); - WriteChar(bos, wavTag); - WriteChar(bos, FmtHdrID); - WriteInt(bos,FmtHdrLeth); - WriteShort(bos,FormatTag); - WriteShort(bos,Channels); - WriteInt(bos,SamplesPerSec); - WriteInt(bos,AvgBytesPerSec); - WriteShort(bos,BlockAlign); - WriteShort(bos,BitsPerSample); - WriteChar(bos,DataHdrID); - WriteInt(bos,DataHdrLeth); - bos.flush(); - byte[] r = bos.toByteArray(); - bos.close(); - return r; - } - - private void WriteShort(ByteArrayOutputStream bos, int s) throws IOException { - byte[] mybyte = new byte[2]; - mybyte[1] =(byte)( (s << 16) >> 24 ); - mybyte[0] =(byte)( (s << 24) >> 24 ); - bos.write(mybyte); - } - - - private void WriteInt(ByteArrayOutputStream bos, int n) throws IOException { - byte[] buf = new byte[4]; - buf[3] =(byte)( n >> 24 ); - buf[2] =(byte)( (n << 8) >> 24 ); - buf[1] =(byte)( (n << 16) >> 24 ); - buf[0] =(byte)( (n << 24) >> 24 ); - bos.write(buf); - } - - private void WriteChar(ByteArrayOutputStream bos, char[] id) { - for (char c : id) { - bos.write(c); - } - } -} diff --git a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavUtils.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavUtils.java deleted file mode 100755 index 068cc6e..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/pcm/WavUtils.java +++ /dev/null @@ -1,48 +0,0 @@ -package ai.qiwu.com.tts_service.common.pcm; - -import lombok.extern.slf4j.Slf4j; - -import java.io.File; -import java.io.RandomAccessFile; - -/** - * 封装的生成wav文件的工具类 - */ -@Slf4j -public class WavUtils { - private static final String TAG = WavUtils.class.getSimpleName(); - /** - * 生成wav格式的Header - * wave是RIFF文件结构,每一部分为一个chunk,其中有RIFF WAVE chunk, - * FMT Chunk,Fact chunk(可选),Data chunk - * - * @param totalAudioLen 不包括header的音频数据总长度 - * @param sampleRate 采样率,也就是录制时使用的频率 - * @param channels audioRecord的频道数量 - * @param sampleBits 位宽 - */ - public static byte[] generateWavFileHeader(int totalAudioLen, int sampleRate, int channels, int sampleBits) { - WavFileHeader wavHeader = new WavFileHeader(totalAudioLen, sampleRate, (short) channels, (short) sampleBits); - return wavHeader.getHeader(); - } - - - /** - * 将header写入到pcm文件中 不修改文件名 - * - * @param file 写入的pcm文件 - * @param header wav头数据 - */ - public static void writeHeader(File file, byte[] header) { - if (!file.isFile()) { - return; - } - - try (RandomAccessFile wavRaf = new RandomAccessFile(file, "rw")) { - wavRaf.seek(0); - wavRaf.write(header); - } catch (Exception e) { - log.error("{},pcm转换成wav出错,{}", TAG, e.toString()); - } - } -} 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 deleted file mode 100644 index fa0140b..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioCommon.java +++ /dev/null @@ -1,208 +0,0 @@ -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 deleted file mode 100644 index 109b736..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConcat.java +++ /dev/null @@ -1,246 +0,0 @@ -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 deleted file mode 100644 index 1734e52..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioConverter.java +++ /dev/null @@ -1,455 +0,0 @@ -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 deleted file mode 100644 index 2133aba..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/AudioDecoder.java +++ /dev/null @@ -1,78 +0,0 @@ -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 deleted file mode 100644 index 75cf901..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/MixingAudioInputStream.java +++ /dev/null @@ -1,351 +0,0 @@ -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 deleted file mode 100644 index 677ba3f..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/Mp3Encoder.java +++ /dev/null @@ -1,338 +0,0 @@ -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 deleted file mode 100644 index d22ad2f..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SampleRateConverter.java +++ /dev/null @@ -1,342 +0,0 @@ -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 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{ - 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{ - 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; -// int 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(); -// bitRate = audioInfo.getBitRate(); -// changedRateList.add(path); -// first = false; -// continue; -// } -// -// if (mouldSampleRate != audioInfo.getSamplingRate() || channel != audioInfo.getChannels() || bitRate != audioInfo.getBitRate()) { -//// log.warn("{} different",path); -// final Integer index = i; -// final Integer sr = mouldSampleRate; -// final Integer cl = channel; -// final Integer br = bitRate; -// Future future = TTService.POOL.submit(() -> { -// try { -// String tempMp3Path = path.substring(0, path.lastIndexOf("."))+SUFFIX_MP3; -// ffmepg(sourceObject, audioInfo, tempMp3Path, sr,cl,br); -// 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, int bitrate) throws EncoderException { -// AudioAttributes audio = new AudioAttributes(); -// audio.setCodec("libmp3lame"); -//// audio.setBitRate(audioInfo.getBitRate()); -// System.out.println("bitrate"+bitrate); -// audio.setBitRate(bitrate); -// 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 deleted file mode 100644 index 9d2dacc..0000000 --- a/tts_service/src/main/java/ai/qiwu/com/tts_service/common/sound/SequenceAudioInputStream.java +++ /dev/null @@ -1,240 +0,0 @@ -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/service/Test.java b/tts_service/src/main/java/ai/qiwu/com/tts_service/service/Test.java index 433020a..e8a5fab 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 @@ -2,41 +2,18 @@ package ai.qiwu.com.tts_service.service; import ai.qiwu.com.tts_service.common.OkHttp3Utils; import ai.qiwu.com.tts_service.common.TTSUtils; -import ai.qiwu.com.tts_service.common.TTServiceUtil; -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; import ai.qiwu.com.tts_service.pojo.upload.UploadOneSenData; -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.alibaba.fastjson.TypeReference; import com.csvreader.CsvReader; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.springframework.util.CollectionUtils; - -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; -import java.net.URLEncoder; import java.nio.charset.Charset; 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; -import static ai.qiwu.com.tts_service.pojo.TtsLsType.*; /** * @author 苗权威