// Q: How do I play an audio file?

import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

public class PlaySound
{

	public static void main( String[] args )
	{
		System.out.println("Playing sound 1.");
		playSound("gameover.wav",0,-1);
		System.out.println("Playing sound 2.");
		playSound("bonus2.wav",0,-1);
		System.out.println("Done.");
	}


	public static void playSound( String filename, int loopTimes, long duration )
	{
		final String _filename  = filename;
		final int    _loopTimes = loopTimes; // how many times to repeat after playing once.  0 to only play once, -1 to loop forever
		final long   _duration  = duration;  // how many milliseconds to play total, or -1 to play until done.

		Thread t = new Thread() {
			public void run()
			{
				try {
					File soundFile = new File(_filename);
					AudioInputStream ais = AudioSystem.getAudioInputStream(soundFile);
					DataLine.Info info = new DataLine.Info( Clip.class, ais.getFormat() );
					Clip clip = (Clip) AudioSystem.getLine( info );
					clip.open( ais );
					clip.loop(_loopTimes);
					long ms = _duration;
					if ( ms < 0 )
						ms = (int) Math.ceil((_loopTimes+1)*(clip.getMicrosecondLength()/1000.0));

					clip.start();
					sleep(ms);
					clip.stop();
				}
				catch ( Exception e ) {
					e.printStackTrace();
					return;
				}
			}
		};
		t.start();
		// Taken from http://forum.java.sun.com/thread.jspa?threadID=5223165&messageID=9977417
		//        and http://www.anyexample.com/programming/java/java_play_wav_sound_file.xml

	}

}
