天天看点

java wav 读取_使用Java将WAV文件读入样本数组时,即时转换采样率

我有一组简短的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).我想避免依赖任何外部库.有没有办法自己进行采样率转换?