问题
I'm trying to downsample a .wav audio from 22050 to 8000 using AudioInputStream but the conversion returns me 0 data bytes. Here is the code:
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);
I already checked AudioSystem.isConversionSupported(targetFormat, sourceFormat)
and it returns true. Any idea?
回答1:
I have just tested your code with different audio files and everything seems to work just fine. I can only guess, that you are either testing your code with an empty audio file (bytes == 0) or, that the file you try to convert is not supported by the Java Audio System.
Try using another input file and/or convert your input file to a compatible file, and it should work.
Here is the main method, that worked for me:
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);
}
}
来源:https://stackoverflow.com/questions/21732090/java-downsampling-from-22050-to-8000-gives-zero-bytes