我安装了mp3spi以支持在我的Java 8项目中使用javax.sound *库读取mp3文件。我现在的目标是将mp3写入wav文件。但是,结果不正确。这是最简单格式的代码:
public static void mp3ToWav(InputStream mp3Data) throws UnsupportedAudioFileException, IOException {
AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(mp3Data);
AudioFormat format = mp3Stream.getFormat();
AudioFormat convertFormat = new AudioSystem.write(mp3Stream, Type.WAVE, new File("C:\\temp\\out.wav"));
}
此处概述的另一种方式(mp3 to wav conversion in java):
File mp3 = new File("C:\\music\\greatest-songs-of-all-time\\RebeccaBlack-Friday.mp3");
if(!mp3.exists()) {
throw new FileNotFoundException("couldn't find mp3");
}
FileInputStream fis = new FileInputStream(mp3);
BufferedInputStream bis = new BufferedInputStream(fis);
AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(bis);
AudioFormat sourceFormat = mp3Stream.getFormat();
AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.getSampleRate(), 16,
sourceFormat.getChannels(),
sourceFormat.getChannels() * 2,
sourceFormat.getSampleRate(),
false);
try (final AudioInputStream convert1AIS = AudioSystem.getAudioInputStream(mp3Stream)) {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final AudioInputStream convert2AIS = AudioSystem.getAudioInputStream(convertFormat, convert1AIS);
System.out.println("Length is: " + mp3Stream.getFrameLength() + " div by " + mp3Stream.getFormat().getFrameRate());
byte [] buffer = new byte[8192];
int iteration = 0;
while(true){
int readCount = convert2AIS.read(buffer, 0, buffer.length);
if(readCount == -1){
break;
}
baos.write(buffer, 0, readCount);
iteration++;
}
System.out.println("completed with iteration: " + iteration);
FileOutputStream fw = new FileOutputStream("C:\\temp\\out-2.wav");
fw.write(baos.toByteArray());
fw.close();
}
bis.close();
fis.close();
这会从压缩的4-5 mb的mp3生成一个超过30 mb的文件,但它不能用作有效的WAV文件。
对我有用的方法涉及使用JLayer Converter类,但是,因为我想做一些其他处理,比如切掉部分音频,修改音量和播放速度等等,我觉得我可能会更好与本地图书馆合作。
答案 0 :(得分:2)
打开mp3流后,通常必须在将其写入文件之前对其进行转换。
像这样(未经测试):
public static void mp3ToWav(File mp3Data) throws UnsupportedAudioFileException, IOException {
// open stream
AudioInputStream mp3Stream = AudioSystem.getAudioInputStream(mp3Data);
AudioFormat sourceFormat = mp3Stream.getFormat();
// create audio format object for the desired stream/audio format
// this is *not* the same as the file format (wav)
AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
sourceFormat.getSampleRate(), 16,
sourceFormat.getChannels(),
sourceFormat.getChannels() * 2,
sourceFormat.getSampleRate(),
false);
// create stream that delivers the desired format
AudioInputStream converted = AudioSystem.getAudioInputStream(convertFormat, mp3Stream);
// write stream into a file with file format wav
AudioSystem.write(converted, Type.WAVE, new File("C:\\temp\\out.wav"));
}