无聊的时候玩玩讯飞tts,文字转语音,可是转出的语音是PCM格式的,无奈只好找转格式的代码。网上千篇一律,互相抄啊,终于找到可用的,但是语音却失真了(鼻音太重,小丸子的声音比蜡笔小新还重。。),只好自己研究。。
后来经过一番思考,java本身是有播放语音文件的能力,网上搜刮了一篇java播放pcm的代码:
public class PcmPlayer {
public static void playPcm(File file) {
try {
int offset = 0;
int bufferSize = Integer.valueOf(String.valueOf(file.length()));
byte[] audioData = new byte[bufferSize];
InputStream in = new FileInputStream(file);
in.read(audioData);
float sampleRate = 16000;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
// sampleRate - 每秒的样本数
// sampleSizeInBits - 每个样本中的位数
// channels - 声道数(单声道 1 个,立体声 2 个)
// signed - 指示数据是有符号的,还是无符号的
// bigEndian - 指示是否以 big-endian 字节顺序存储单个样本中的数据(false 意味着
// little-endian)。
AudioFormat af = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
SourceDataLine.Info info = new DataLine.Info(SourceDataLine.class, af, bufferSize);
SourceDataLine sdl = (SourceDataLine) AudioSystem.getLine(info);
sdl.open(af);
sdl.start();
while (offset < audioData.length) {
offset += sdl.write(audioData, offset, bufferSize);
}
} catch (LineUnavailableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
可以直接播放PCM,然后突发奇想:既然能播放就能保存。想到就做:
public class Pcm2Wav {
public static void main(String[] args) throws Exception {
parse("d:/1.pcm", "d:/11.wav");
}
public static void parse(String source, String target) throws Exception {
float sampleRate = 16000;
int sampleSizeInBits = 16;
int channels = 1;
boolean signed = true;
boolean bigEndian = false;
AudioFormat af = new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
File sourceFile = new File(source);
FileOutputStream out = new FileOutputStream(new File(target));
AudioInputStream audioInputStream = new AudioInputStream(new FileInputStream(sourceFile), af, sourceFile.length());
AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, out);
audioInputStream.close();
out.flush();
out.close();
}
}
结果真的可以直接转换了,而且效果和pcm一样好。