我正在尝试使用AudioInputStream将.wav音频从22050下采样到8000但转换返回0个数据字节。这是代码:
AudioInputStream ais;
AudioInputStream eightKhzInputStream = null;
ais = AudioSystem.getAudioInputStream(file);
if (ais.getFormat().getSampleRate() == 22050f) {
AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(file);
AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
AudioFormat sourceFormat = ais.getFormat();
AudioFormat targetFormat = new AudioFormat(
sourceFormat.getEncoding(),
8000f,
sourceFormat.getSampleSizeInBits(),
sourceFormat.getChannels(),
sourceFormat.getFrameSize(),
8000f,
sourceFormat.isBigEndian());
eightKhzInputStream = AudioSystem.getAudioInputStream(targetFormat, ais);
int nWrittenBytes = 0;
nWrittenBytes = AudioSystem.write(eightKhzInputStream, targetFileType, file);
我已经检查过AudioSystem.isConversionSupported(targetFormat, sourceFormat)
并返回true。有什么想法吗?
答案 0 :(得分:1)
我刚用不同的音频文件测试了你的代码,一切似乎都运行得很好。我只能猜测,您要么使用空音频文件(bytes == 0)测试代码,要么Java音频系统不支持您尝试转换的文件。
尝试使用其他输入文件和/或将输入文件转换为兼容文件,它应该可以正常工作。
这是主要方法,对我有用:
public static void main(String[] args) throws InterruptedException, UnsupportedAudioFileException, IOException {
File file = ...;
File output = ...;
AudioInputStream ais;
AudioInputStream eightKhzInputStream = null;
ais = AudioSystem.getAudioInputStream(file);
AudioFormat sourceFormat = ais.getFormat();
if (ais.getFormat().getSampleRate() == 22050f) {
AudioFileFormat sourceFileFormat = AudioSystem.getAudioFileFormat(file);
AudioFileFormat.Type targetFileType = sourceFileFormat.getType();
AudioFormat targetFormat = new AudioFormat(
sourceFormat.getEncoding(),
8000f,
sourceFormat.getSampleSizeInBits(),
sourceFormat.getChannels(),
sourceFormat.getFrameSize(),
8000f,
sourceFormat.isBigEndian());
if (!AudioSystem.isFileTypeSupported(targetFileType) || ! AudioSystem.isConversionSupported(targetFormat, sourceFormat)) {
throw new IllegalStateException("Conversion not supported!");
}
eightKhzInputStream = AudioSystem.getAudioInputStream(targetFormat, ais);
int nWrittenBytes = 0;
nWrittenBytes = AudioSystem.write(eightKhzInputStream, targetFileType, output);
System.out.println("nWrittenBytes: " + nWrittenBytes);
}
}