How do you output sound in Java?

Asked 2 years ago, Updated 2 years ago, 79 views

I want to make a sound on my program, what can I do?

java audio

2022-09-22 22:14

1 Answers

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

I turned it around and it worked well. But I think only the .wav file will go back.


2022-09-22 22:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.