2014-12-23 100 views
0

我正在製作一個有音樂組件的程序。基本上,當按下某些按鈕時,我想播放特定的歌曲文件。在Java中我一直在播放聲音,但沒有爲我工作。我目前在教程中找到一些代碼,但我不確定如何指定文件。我不斷收到一個FileNotFoundExecption,所以我明顯引用文件不正確。我的桌面上有.wav文件,我也在我的項目的資源源文件夾中。部分代碼如下,我如何引用文件的任何想法?在Java中播放聲音文件

public static void main(String[] args) throws Exception { 

    // specify the sound to play 
    // (assuming the sound can be played by the audio system) 
    File soundFile = new File("/desktop/14_Wonderland.wav"); 
    AudioInputStream sound = AudioSystem.getAudioInputStream(soundFile); 

    // load the sound into memory (a Clip) 
    DataLine.Info info = new DataLine.Info(Clip.class, sound.getFormat()); 
    Clip clip = (Clip) AudioSystem.getLine(info); 
    clip.open(sound); 

    // due to bug in Java Sound, explicitly exit the VM when 
    // the sound has stopped. 
    clip.addLineListener(new LineListener() { 
     public void update(LineEvent event) { 
      if (event.getType() == LineEvent.Type.STOP) { 
       event.getLine().close(); 
       System.exit(0); 
      } 
     } 
    }); 

    // play the sound clip 
    clip.start(); 
} 
+1

'/ desktop/14_Wonderland.wav',不會讓你到桌面上..請參閱[this](http://stackoverflow.com/questions/1080634/how-to-get-the-desktop-path -in-java)或[this](http://stackoverflow.com/questions/9981594/get-absolute-desktop-path)。 [Here](http://stackoverflow.com/questions/570401/in-java-under-windows-how-do-i-find-a-redirected-desktop-folder)是另外一個 – chancea

回答

1

如果你都很難找到一個文件的一些原因,我知道這是不是非常適合大多數情況下,但你可以嘗試使用JFileChooser(我聯繫的例子)。

由此,您可以使用找到的文件,也可以輸出所選文件的位置,以便查看如何爲文件路徑建模。我希望這有幫助!

快樂編碼!如果您有任何問題,請留下評論。

0

如果您不介意在播放聲音時打開默認音樂應用程序,則可以執行此操作: 對於Mac OS X:Desktop.open(FilePath); 對於Windows:Runtime.exec(FilePath);

0

我知道它並沒有回答你有關文件異常(其他人已經做過)的問題,但是你可以使用這段代碼來播放聲音(你可能需要使用它以適應你的需求):

import java.io.File; 
import java.io.IOException; 
import javax.sound.sampled.AudioFormat; 
import javax.sound.sampled.AudioInputStream; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.Clip; 
import javax.sound.sampled.LineUnavailableException; 
import javax.sound.sampled.UnsupportedAudioFileException; 

public class PlaySound { 
    private static boolean tryToInterruptSound = false; 
    private static long mainTimeOut = 3000; 
    private static long startTime = System.currentTimeMillis(); 

    public static synchronized Thread playSound(final File file) { 

     Thread soundThread = new Thread() { 
      @Override 
      public void run() { 
       try{ 
        Clip clip = null; 
        AudioInputStream inputStream = null; 
        clip = AudioSystem.getClip(); 
        inputStream = AudioSystem.getAudioInputStream(file); 
        AudioFormat format = inputStream.getFormat(); 
        long audioFileLength = file.length(); 
        int frameSize = format.getFrameSize(); 
        float frameRate = format.getFrameRate(); 
        long durationInMiliSeconds = 
          (long) (((float)audioFileLength/(frameSize * frameRate)) * 1000); 

        clip.open(inputStream); 
        clip.start(); 
        System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound started playing!"); 
        Thread.sleep(durationInMiliSeconds); 
        while (true) { 
         if (!clip.isActive()) { 
          System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound got to it's end!"); 
          break; 
         } 
         long fPos = (long)(clip.getMicrosecondPosition()/1000); 
         long left = durationInMiliSeconds - fPos; 
         System.out.println("" + (System.currentTimeMillis() - startTime) + ": time left: " + left); 
         if (left > 0) Thread.sleep(left); 
        } 
        clip.stop(); 
        System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound stoped"); 
        clip.close(); 
        inputStream.close(); 
       } catch (LineUnavailableException e) { 
        e.printStackTrace(); 
       } catch (UnsupportedAudioFileException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } catch (InterruptedException e) { 
        System.out.println("" + (System.currentTimeMillis() - startTime) + ": sound interrupted while playing."); 
       } 
      } 
     }; 
     soundThread.setDaemon(true); 
     soundThread.start(); 
     return soundThread; 
    } 

    public static void main(String[] args) { 
     Thread soundThread = playSound(new File("C:\\Booboo.wav")); 
     System.out.println("" + (System.currentTimeMillis() - startTime) + ": playSound returned, keep running the code"); 
     try { 
      Thread.sleep(mainTimeOut); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     if (tryToInterruptSound) { 
      try { 
       soundThread.interrupt(); 
       Thread.sleep(1); 
       // Sleep in order to let the interruption handling end before 
       // exiting the program (else the interruption could be handled 
       // after the main thread ends!). 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     System.out.println("" + (System.currentTimeMillis() - startTime) + ": End of main thread; exiting program " + 
       (soundThread.isAlive() ? "killing the sound deamon thread" : "")); 
    } 
} 

嘗試在類路徑中使用絕對文件路徑或路徑來解決FileNotFound異常。

+0

謝謝!既然我修復了文件路徑,這個代碼和之前使用的代碼似乎都在正確的軌道上。但是,我現在得到一個LineUnavailableException,因爲我請求的緩衝區太大了。我現在正在研究這個異常 – user4305589