我有一组简短的 WAV 文件,我想使用各种数字信号处理算法在 Java 中处理这些文件。为此,我需要获取一个 int 值样本数组,以 11025 Hz 帧速率编码。
源文件有几种不同的采样率,包括 11025 Hz 和 44100 Hz。这是我试图用来阅读它们的代码:
// read the WAV file
FileInputStream fileInputStream = new FileInputStream(new File("test.wav"));
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(fileInputStream );
// copy the AudioInputStream to a byte array called buffer
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[4096];
int tempBytesRead = 0;
int byteCounter = 0;
while ((tempBytesRead = audioInputStream.read(data, 0, data.length)) != -1) {
bos.write(data, 0, tempBytesRead);
byteCounter += tempBytesRead;
}
bos.close();
byte[] buffer = bos.toByteArray();
AudioFileFormat audioFileFormat = new AudioFileFormat(AudioFileFormat.Type.WAVE, audioInputStream.getFormat(), (int)audioInputStream.getFrameLength());
// get the resulting sample array
int[] samples = new int[audioFileFormat.getFrameLength()];
for (int i = 0; i < samples.length; i++) {
samples[i] = getSampleValue(i); // the getSampleValue method reads the sample values from the "buffer" array, handling different encoding types like PCM unsigned/signed, mono/stereo, 8 bit/16 bit
}
// RESULT: the "samples" array
问题是,代码不能正确处理不同的采样率。因此,对于 44100 Hz 帧速率,我得到的样本数量是 11025 Hz 帧速率的四倍。我希望生成的样本数组使用 11025 Hz 帧速率,而不考虑源文件的帧速率。在读取 AudioInputStream 时,我尝试强制 Java 为我转换帧速率,但出现类似于以下异常的异常:
java.lang.IllegalArgumentException: Unsupported conversion: PCM_SIGNED 11025.0 Hz, 16 bit, mono, 2 bytes/frame, 44100.0 frames/second, little-endian from PCM_SIGNED 44100.0 Hz, 16 bit, mono, 2 bytes/frame, little-endian
at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:955)
我阅读了 Java Sound API 教程:http: //java.sun.com/docs/books/tutorial/sound/converters.html。Java Sound API 似乎不支持我的操作系统(Windows 7)的这种转换。而且我想避免对任何外部库的依赖。有什么办法可以自己进行采样率转换吗?