2012-02-08 159 views
0

儘管sun.audio API表示.wav是一個受支持的文件,顯然這是我擁有的文件一定不是。一個.aiff文件現在正在工作,但不是以這種方式,我發現了一個更好的方式,雖然有點複雜。在Java程序中聲音播放

String strFilename = "C:\\Documents and Settings\\gkehoe\\Network\\GIM\\Explode.aiff"; 
    File soundFile = new File(strFilename); 

    AudioInputStream audioInputStream = null; 
    try 
    { 
     audioInputStream = AudioSystem.getAudioInputStream(soundFile); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 

    AudioFormat audioFormat = audioInputStream.getFormat(); 
    SourceDataLine line = null; 
    DataLine.Info info = new DataLine.Info(SourceDataLine.class, 
              audioFormat); 
    try 
    { 
     line = (SourceDataLine) AudioSystem.getLine(info); 

     /* 
      The line is there, but it is not yet ready to 
      receive audio data. We have to open the line. 
     */ 
     line.open(audioFormat); 
    } 
    catch (LineUnavailableException e) 
    { 
     e.printStackTrace(); 
     System.exit(1); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
     System.exit(1); 
    } 
    line.start(); 

    int nBytesRead = 0; 
    byte[] abData = new byte[EXTERNAL_BUFFER_SIZE]; 
    while (nBytesRead != -1) 
    { 
     try 
     { 
      nBytesRead = audioInputStream.read(abData, 0, abData.length); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     if (nBytesRead >= 0) 
     { 
      int nBytesWritten = line.write(abData, 0, nBytesRead); 
     } 
    } 
    line.drain(); 

    /* 
     All data are played. We can close the shop. 
    */ 
    line.close(); 
+0

你有沒有看到這個http://stackoverflow.com/questions/26305/how-can-i-play-sound-in-java#comment4884807_26311? – Mob 2012-02-08 17:41:12

+0

是的,我做到了,但那是我從這個代碼。它不起作用。 – 2012-02-08 18:18:21

+0

你有問題嗎? – 2012-02-08 19:39:17

回答

0

根據source code它不被識別爲支持的文件格式。

+0

是不支持的.wav嗎?我的理解是這是支持的類型之一。 – 2012-02-08 17:58:46

+0

我沒有這麼說。它只是不被認可。你有沒有嘗試過別的。 – teodozjan 2012-02-08 18:12:55

0

支持Wav文件,但有許多變量,其中一些變量不受支持。 例如,如果wav編碼爲48000而不是44100,或者編碼爲24或32位而不是16位編碼,則可能會遇到無法識別的格式異常。

你得到了什麼確切的錯誤?

什麼是wav文件的規格(屬性)?

使用諸如Audacity之類的工具,可以從一個wav轉換爲兼容的wav。我用於wav文件的格式具有以下屬性:

16-bit encoding 
little endian 
44100 sample rate 
stereo 

我沒有真正仔細看過代碼示例本身。我喜歡this播放示例。