Last day I posting about play midi java , the purpose of that source is to play sound effect in game, but as that tittle said, its only able to play midi format, and its hard to find sfx in midi format, most of them is in wav format so I change my mind and using wav format for my game. As this post title, I want to show you how to play sound in java as simple as possible,  in this sample I using wav format.

The first solution is using java.applet and java.net resources, I tested it and it working even in J2SE, here we go :

import java.applet.*;
import java.net.*;
----------------------------------------------
try {
AudioClip clip1 = Applet.newAudioClip(
new URL(“file://c:/blah/foo.wav”));
clip1.play();
} catch (MalformedURLException murle) {
System.out.println(murle);
}

Therefore second solution and I recommend one is using javax.sound.sampled , here we go :

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
----------------------------------------------
Clip clip2 = null;

if (clip2==null) {
clip2 = AudioSystem.getClip();
// Use URL (instead of File) to read from disk and JAR.
URL url = this.getClass().getResource("resources/LASER1.WAV");
// Set up an audio input stream piped from the sound file.
AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url);
// Get a clip resource.
// Open audio clip and load samples from the audio input stream.
clip2.open(audioInputStream);
}
// Stop the player if it is still running
if (clip2.isRunning()) clip2.stop();
clip2.setFramePosition(0); // rewind to the beginning
clip2.start();     // Start playing

Quite simple and easy isn’t it? Thanks for reading, hope the post help you. You can follow my twitter for info about my newest post.