2017-03-26 162 views
-1

我想將音頻文件轉換爲字節數組。目前,我做到了,我想知道,如果它的工作原理:如何將音頻文件轉換爲字節數組

private static AudioFormat getFormat() { 
    float sampleRate = 44100; 
    int sampleSizeInBits = 16; 
    int channels = 1; 
    boolean signed = true; 
    boolean bigEndian = true; 
    return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, 
      bigEndian); 
} 

public static byte[] listenSound(File f) { 

    AudioInputStream din = null; 
    AudioInputStream outDin = null; 
    PCM2PCMConversionProvider conversionProvider = new PCM2PCMConversionProvider(); 

    try { 
     AudioInputStream in = AudioSystem.getAudioInputStream(f); 
     AudioFormat baseFormat = in.getFormat(); 
     AudioFormat decodedFormat = new AudioFormat(
        AudioFormat.Encoding.PCM_SIGNED, 
        baseFormat.getSampleRate(), 
        16, 
        baseFormat.getChannels(), 
        baseFormat.getChannels() * 2, 
        baseFormat.getSampleRate(), 
        false); 

     din = AudioSystem.getAudioInputStream(decodedFormat, in); 

     if (!conversionProvider.isConversionSupported(getFormat(), decodedFormat)) { 
      System.out.println("Conversion Not Supported."); 
      System.exit(-1); 
     } 

     outDin = conversionProvider.getAudioInputStream(getFormat(), din); 

     ByteArrayOutputStream out = new ByteArrayOutputStream(); 
     int n = 0; 
     byte[] buffer = new byte[1024]; 

     while (true) { 
      n++; 
      if (n > 1000) 
       break; 

      int count = 0; 
      count = outDin.read(buffer, 0, 1024); 

      if (count > 0) { 
       out.write(buffer, 0, count); 
      } 
     } 
     in.close(); 
     din.close(); 
     outDin.close(); 
     out.flush(); 
     out.close(); 

     //byte[] b=out.toByteArray(); 
     //for(int i=0; i<b.length; i++) 
     //System.out.println("b = "+b[i]); 
     return out.toByteArray(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

該字節數組數據實際上被稱爲時域我需要確保,如果將其轉化這個數據與離散傅立葉頻域之前的作品。 感謝您的幫助!

+0

以什麼格式? WAV? MP3? 3GP? FLAC? MMF? OGG? RA? WMA?其他一些格式? –

+0

您是否在談論入口中的文件?如果是的話,它可以格式爲MP3或WAV – kone

回答

0

通常的實際字節數處理後從調用返回像

count = outDin.read(buffer, 0, 1024); 

所以除了後處理1000塊你目前的硬盤休息,如果API事實上確實返回字節數,你應該檢查它:

int size_chunk = 1024 
byte[] buffer = new byte[size_chunk]; 
boolean keep_streaming = true; 
while (keep_streaming) { 
    n++; 
    if (n > 1000) { // troubleshooting ONLY remove later 

     keep_streaming = false; 
    } 

    int count = 0; 
    count = outDin.read(buffer, 0, size_chunk); 

    if (count > 0) { 
     out.write(buffer, 0, count); 
    } 

    if (count < size_chunk) { // input stream has been consumed 
     keep_streaming = false; 
    } 
} 

你沒有提供的鏈接,API文檔,所以我無法證實,但假設outDin.read將輸出實際處理的字節數,上面的代碼將正確地只輸出字節來匹配輸入等會導致一個如果輸入小於1兆數據,則輸出較小(原始邏輯盲目產生一個1兆輸出,僅在看到1000個塊後才停止...它還假定您打算根據您的行在1兆數據後截斷輸入

if (n > 1000) { // troubleshooting ONLY remove later 

     keep_streaming = false; 
    } 
+0

我編輯了我的答案 –

相關問題