我遇到了有关音频解码的问题。我有用于mp3解码的SPIMP3库,我正在尝试解码mp3并将它们存储到一个字节数组中。
这就是问题,当我尝试解码一首2分钟的mp3歌曲时,它给了我以下字节:
[-1,0,42,-115,-45,0,14 ......等]。
但是当我把那个mp3切成两半并尝试解码前半部分时,我得到以下字节:
[1,0,0,65,-97,135,-64,32 ......等]
奇怪的是它们不匹配。这里唯一不同的是音频长度,但我正在解码两个mp3样本的第一部分是相同的。
这是我的代码:
public void testPlay(String mp3) {
try {
File file = new File(mp3);
AudioInputStream in = AudioSystem.getAudioInputStream(file);
AudioInputStream din = null;
AudioFormat baseFormat = in.getFormat();
AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
baseFormat.getSampleRate(),
16,
baseFormat.getChannels(),
baseFormat.getChannels() * 2,
baseFormat.getSampleRate(),
false);
din = AudioSystem.getAudioInputStream(decodedFormat, in);
play(decodedFormat, din);
spi(decodedFormat, in);
in.close();
} catch (Exception e) {
System.out.println("MP3");
}
}
private void play(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] data = new byte[4096];
SourceDataLine line = getLine(targetFormat);
int nBytesRead = 0, nBytesWritten = 0;
while (nBytesRead != -1) {
nBytesRead = din.read(data, 0, data.length);
if (nBytesRead != -1) {
nBytesWritten = line.write(data, 0, nBytesRead);
out.write(data, 0, 4096);
}
}
byte[] audio = out.toByteArray();
}
这是预期的事情还是我的代码有问题???
如何更改我的代码以获取我的mp3匹配部分的相同字节?
谢谢。
答案 0 :(得分:3)
这一行应该是:
out.write(data, 0, nBytesRead);