小编典典

如何用Java播放声音?

java

我希望能够在程序中播放声音文件。我应该去哪里看?


阅读 351

收藏
2020-02-28

共1个答案

小编典典

我写了下面的代码,效果很好。但我认为它仅适用于.wav格式。

public static synchronized void playSound(final String url) {
  new Thread(new Runnable() {
  // The wrapper thread is unnecessary, unless it blocks on the
  // Clip finishing; see comments.
    public void run() {
      try {
        Clip clip = AudioSystem.getClip();
        AudioInputStream inputStream = AudioSystem.getAudioInputStream(
          Main.class.getResourceAsStream("/path/to/sounds/" + url));
        clip.open(inputStream);
        clip.start(); 
      } catch (Exception e) {
        System.err.println(e.getMessage());
      }
    }
  }).start();
}
2020-02-28