2012-02-08 157 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播放示例。