audio – How can I play sound in Java?

audio – How can I play sound in Java?

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));;
      } catch (Exception e) {

A bad example:

import*;    //import the package

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);         

// Use the static class member player from class AudioPlayer to play
// clip.

// Similarly, to stop the audio.

audio – How can I play sound in Java?

I didnt want to have so many lines of code just to play a simple damn sound. This can work if you have the JavaFX package (already included in my jdk 8).

private static void playSound(String sound){
    // cl is the ClassLoader for the current class, ie. CurrentClass.class.getClassLoader();
    URL file = cl.getResource(sound);
    final Media media = new Media(file.toString());
    final MediaPlayer mediaPlayer = new MediaPlayer(media);;

Notice : You need to initialize JavaFX. A quick way to do that, is to call the constructor of JFXPanel() once in your app :

    JFXPanel fxPanel = new JFXPanel();

Leave a Reply

Your email address will not be published. Required fields are marked *