How can I play sound in Java?

后端 未结 10 978
傲寒
傲寒 2020-11-22 04:38

I want to be able to play sound files in my program. Where should I look?

10条回答
  •  星月不相逢
    2020-11-22 05:12

    I wrote the following code that works fine. But I think it only works with .wav format.

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

提交回复
热议问题