I am facing a problem regarding audio decoding. I have the SPIMP3 library for mp3 decoding and I am trying to decode mp3's and storing them to an array of bytes.
Here is the thing, when I try to decode a 2 minute mp3 song it gives me, for example, the following bytes:
[ -1, 0, 42, -115, -45, 0, 14 ... etc].
But when I cut that mp3 in half and try to decode the first half I get the following bytes:
[ 1, 0, 0, 65, -97, 135, -64, 32 ...etc]
The weird thing is that they don't match. The only thing that differs here is the audio length, but I am decoding the first part of both of the mp3 samples which is the same.
Here is my code:
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();
}
Is this something to be expected or is there a problem on my code???
How can I change my code to get the same bytes for the matching part of my mp3?
Thank you.
this line should be:
out.write(data, 0, nBytesRead);