我有一組簡短的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).我想避免依賴任何外部庫.有沒有辦法自己進行采樣率轉換?