July 7th, 2008
More Java Sounds
Here’s an update to my last post: My cousin, Dave. (Way to go, Dave!) submitted this example of another (simpler) way to play sound files:
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
public class SimpleSoundPlayer2 {
public static void main( String[] args )
{
// The audio file to play
String audioFile = "/1-welcome.wav";
// Check that the resource is available
URL url = SimpleSoundPlayer2.class.getResource(audioFile);
if( url == null ) {
System.out.println("Resource not found.");
System.exit(1);
}
try {
playSound(url);
} catch( IOException e ) {
System.err.println("IOException occured: " + e );
e.printStackTrace();
System.exit(1);
}
}
public static void playSound( URL url ) throws IOException {
AudioInputStream audioStream = null;
try {
audioStream = AudioSystem.getAudioInputStream( url );
} catch( UnsupportedAudioFileException e ) {
System.err.println("The audio file is not a recognized format.");
return;
}
// Print out some info about the sound
System.out.printf("URL: %s \nFormat: %s\n", url.toString(),
audioStream.getFormat().toString() );
try {
// Create the clip and open the stream
Clip clip = AudioSystem.getClip();
clip.open(audioStream);
// Start playing the sound
clip.start();
// Wait until the sound finishes playing
while (clip.isActive()) {
try { Thread.sleep(99); } catch (Exception e) {break;}
}
// Close the clip
clip.close();
} catch (LineUnavailableException e ) {
System.err.println("Unable to create Clip: " + e);
e.printStackTrace();
System.exit(1);
}
}
}
I believe the same rules apply here as far as where you put for resource files and the pathing used to find them.

