Antoine Neveux

Yet another blog about stuff.

Playing wav sounds with Java

Hi everybody,

A few days ago, I wanted to add some audio notifications in an application, so I searched on the Internet for a way to do this, and I found quite a lot of different pieces of source code for doing such a thing. First of all, I found an easy way to play sounds in Java, using java.applet.* classes. Using this kind of API is really easy, but I was not really happy about using applet.* classes. I read some other websites, and found another set of classes to use: javax.sound.sampled.*.

Once again, I found some examples with these classes, but the source code was still too complicated. So I had a look at the APIs and wrote my own source code, trying to keep it as readable as possible. I decided to play the sound in a particular thread, so as to ease the use of the player. So here is my code:

As you can see, you just have to create a new SoundPlayer object, and give it an AudioInputStream. Then, just start the thread and it’s ok. If you want to wait for the sound to be played before doing anything else, just call the join() method on the Thread. Here is an example on how to use it:

Using this piece of source code, it’s now really easy to play wav sounds using Java.

If you have another easier alternative, feel free to share it ;)