2014-02-12 24 views
1

我試圖使用AudioInputStream從22050下采樣.wav音頻到8000,但轉換返回我0數據字節。以下是代碼:Java - 下采樣從22050到8000給出零字節

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。任何想法?

回答

1

我剛剛用不同的音頻文件測試了你的代碼,一切似乎都很好。我只能猜測,你要麼用一個空的音頻文件(字節== 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); 
    } 
} 
+0

AIS指向一個真正的文件:ais.available()返回26000左右,這是一個標準的WAV文件。畢竟,如果這種格式對於Java音頻系統來說是未知的,那麼在請求AudioInputStream時,我會得到和異常,不是嗎? –

+0

是的,你應該得到一個異常......無論如何,你的代碼在我的電腦上工作,我會在第二個工作主要方法 – Balder

+0

我已經添加了一個檢查,如果轉換實際上支持代碼。試試看,如果IllegalStateException拋出或不。 – Balder