import	java.io.File;
import	java.io.IOException;

import	javax.sound.sampled.AudioFormat;
import	javax.sound.sampled.AudioInputStream;
import	javax.sound.sampled.AudioSystem;
import	javax.sound.sampled.Clip;
import	javax.sound.sampled.DataLine;
import	javax.sound.sampled.LineEvent;
import	javax.sound.sampled.LineListener;
import	javax.sound.sampled.LineUnavailableException;


public class ClipPlayer
	implements	LineListener
{
	private Clip		m_clip;


	/*
	 *	The clip will be played nLoopCount + 1 times.
	 */
	public ClipPlayer(File clipFile, int nLoopCount)
	{
		AudioInputStream	audioInputStream = null;
		try
		{
			audioInputStream = AudioSystem.getAudioInputStream(clipFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		if (audioInputStream != null)
		{
			AudioFormat	format = audioInputStream.getFormat();
			DataLine.Info	info = new DataLine.Info(Clip.class, format);
			try
			{
				m_clip = (Clip) AudioSystem.getLine(info);
				m_clip.addLineListener(this);
				m_clip.open(audioInputStream);
			}
			catch (LineUnavailableException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			m_clip.loop(nLoopCount);
		}
		else
		{
			System.out.println("ClipPlayer.<init>(): can't get data from file " + clipFile.getName());
		}
	}



	public void update(LineEvent event)
	{
		if (event.getType().equals(LineEvent.Type.STOP))
		{
			m_clip.close();
		}
		else if (event.getType().equals(LineEvent.Type.CLOSE))
		{
			/*
			 *	There is a bug in the jdk1.3.0.
			 *	It prevents correct termination of the VM.
			 *	So we have to exit ourselves.
			 */
		//	System.exit(0);
		}

	}


/*
	public static void main(String[] args)
	{
		if (args.length != 2)
		{
			System.out.println("ClipPlayer: usage:");
			System.out.println("\tjava ClipPlayer <soundfile> <#loops>");
		}
		else
		{
			File	clipFile = new File(args[0]);
			int		nLoopCount = Integer.parseInt(args[1]);
			ClipPlayer	clipPlayer = new ClipPlayer(clipFile, nLoopCount);
		}
	} */
}
