【发布时间】:2017-01-21 20:54:17
【问题描述】:
我安装了 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 类,但是,因为我想做一些其他处理,比如剪切部分音频、修改音量和播放速度等,我觉得我可能会更好停止使用本机库。
【问题讨论】:
-
我挑战mp3Data的存在;你从哪里得到它,它包含什么?在任何情况下你都需要从字节开始 - 一个字节数组 - 如答案 - 你有那个字节数组吗?
-
AudioFormat convertFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sourceFormat.getSampleRate(), 16, sourceFormat.getChannels(), sourceFormat.getChannels() * 2, sourceFormat.getSampleRate(), false);不要对这些值进行硬编码。使用与源格式相同的值,它可能会像宣传的那样工作。 -
gspasch你可以挑战mp3数据的存在,但我保证它存在!我将修改我的问题以包含该部分代码
-
@AndrewThompson 我按原样离开了 AudioFormat.Encoding.PCM_SIGNED(因为我假设它赋予了 WAV 格式)并将 sourceFormat 用于其他所有内容并出现相同的错误
-
秒码 sn-p 不会创建有效的 wav 文件,而是(可能)创建原始音频文件。一旦我拥有转换后的流
convert2AIS,我只需调用AudioSystem.write(convert2AIS, Type.WAVE, new File("C:\\temp\\out.wav"));,然后让AudioSystem为我编写。