【问题标题】:Playing a sound file in Java在 Java 中播放声音文件
【发布时间】:2014-12-23 19:28:02
【问题描述】:

我正在开发一个包含音乐组件的程序。基本上,当按下某些按钮时,我想播放特定的歌曲文件。我一直在研究用 Java 播放声音,但对我来说还没有任何效果。我目前正在玩一些我在教程中找到的代码,但是我不确定如何指定文件。

我不断收到FileNotFoundExecption,所以我显然错误地引用了该文件。我的桌面上有.wav 文件,我的项目的资源源文件夹中也有它。部分代码如下,关于我如何引用文件的任何想法?

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();
}

【问题讨论】:

  • /desktop/14_Wonderland.wav 不会让您进入桌面。请参阅thisthisHere 是另一个

标签: java eclipse audio


【解决方案1】:

如果由于某种原因您在查找文件时遇到问题,我知道这在大多数情况下并不理想,但您可以尝试使用 JFileChooser(我链接了一个示例)。

由此,您可以只使用找到的文件,也可以输出所选文件的位置,以便了解如何为文件路径建模。我希望这会有所帮助!

编码愉快!如果您有任何问题,请发表评论。

【讨论】:

    【解决方案2】:

    如果您不介意在播放声音时打开默认音乐应用程序, 你可以这样做: 对于 Mac OS X:Desktop.open(FilePath); 对于 Windows:Runtime.exec(FilePath);

    【讨论】:

      【解决方案3】:

      我知道它不能回答您关于文件异常的问题(其他人已经回答了),但您可以使用此代码播放声音(您可能需要稍微玩一下以满足您的需要):

      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 异常。

      【讨论】:

      • 谢谢!既然我修复了文件路径,这段代码和我之前使用的代码似乎都在正确的轨道上。但是,我现在收到 LineUnavailableException,因为我请求的缓冲区太大。我现在正在调查这个异常
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-21
      相关资源
      最近更新 更多