noobtuts

Java Play Sounds

Foreword

Every good video game needs sound. Sound can make a big difference when it comes to the gaming experience. Whole games are based on Sound, for example Singstar or Guitar Hero.

Implementation of the Sound class

We want to play sound files in Java, so let's create a Sound class first:

public class Sound {

}

Now we have a Sound class that does nothing yet. The class will hold our sound related functions. The most easy format to play in Java is the wave format (.wav), and since this is perfectly fine for video games, we will use it.

Implementation of the play function

The function is very straight forward. Obviously we need to open the sound file and then play it somehow. There is one catch though:
What if the same sound is played twice at the same time? For example in a racing game we will need to be able to play two car sounds at once, or even more. To make this possible, we will play each sound in a new thread every time. The result is that we can play several sounds at the same time.

The implementation:

public class Sound {
    public static synchronized void play(final String fileName)
    {
        // Note: use .wav files            
        new Thread(new Runnable() {
            public void run() {
                try {
                    Clip clip = AudioSystem.getClip();
                    AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File(fileName));
                    clip.open(inputStream);
                    clip.start();
                } catch (Exception e) {
                    System.out.println("play sound error: " + e.getMessage() + " for " + fileName);
                }
            }
        }).start();
    }
}

As you can see, we create a new thread and directly fill out its run() method and start it afterwards in line 18. If something went wrong, the function will print out a "play sound error" to the console.

Note: it's a static function, this means that we can use it without creating a new Sound object each time.

Usage example

Let's try it out! We will put a test.wav sound file directly into our project folder. We will then play it like this:

Sound.play("test.wav");

If the file would be in a sub folder, for example Sounds/test.wav, then this would be the way to use it:

Sound.play("Sounds/test.wav");

Summary

A simple play sound function that works perfectly with the .wav file format. The interested reader could now try to extend this function to also play other popular sound formats, like .mp3 or .ogg files.