In one of my projects, I need to resample PCM audio data to a different sample rate. I am using javax.sound.sampled.AudioSystem for this task. The resampling seems to add additional samples at the beginning and end of the frame. Here is a minimal working example:
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Arrays;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
ublic class ResamplingTest {
public static void main(final String[] args) throws IOException {
final int nrOfSamples = 4;
final int bytesPerSample = 2;
final byte[] data = new byte[nrOfSamples * bytesPerSample];
Arrays.fill(data, (byte) 10);
final AudioFormat inputFormat = new AudioFormat(32000, bytesPerSample * 8, 1, true, false);
final AudioInputStream inputStream = new AudioInputStream(new ByteArrayInputStream(data), inputFormat, data.length);
final AudioFormat outputFormat = new AudioFormat(24000, bytesPerSample * 8, 1, true, false);
final AudioInputStream outputStream = AudioSystem.getAudioInputStream(outputFormat, inputStream);
final var resampledBytes = outputStream.readAllBytes();
System.out.println("Expected number of samples after resampling "
+ (int) (nrOfSamples * outputFormat.getSampleRate() / inputFormat.getSampleRate()));
System.out.println("Actual number of samples after resampling " + resampledBytes.length / bytesPerSample);
System.out.println(Arrays.toString(resampledBytes));
}
}
I would expect exactly 3 samples when resampling 4 samples from 32 kHz to 24 kHz. However, the above code generates 5 samples. The number of extra samples seems to depend on the input and output sample rate. For example, if I resample from 8 kHz to 32 kHz, 8 additional samples are generated. Why does resampling add additional samples, and how do I know how many samples are added at the beginning and end of a frame?