import java.io.*;
import javax.sound.sampled.*;

/**
 * Class SoundEngine provides functionality to process sound files.
 * Sounds can be loaded, played, paused, resumed, and stopped.
 *
 * The sound engine can play multiple sounds simultaniously, but only
 * the last sound loaded can be controlled (pased, resumed, etc.).
 *
 * The sound engine accepts files in WAV, AIFF, and AU formats (although
 * not all WAV files - it depends on the encoding in the file).
 *
 * @author Michael Kolling and David J Barnes
 * @version 1.0
 */
public class play
{
    // the following three fields hold information about the sound clip
    // currently loaded in this engine
    //private Clip currentSoundClip = null;
    //private int currentSoundDuration = 0;
    //private int currentSoundFrameLength = 0;

    public play()
    {
    }

	public static void main(String[] args) {
		for (int i=0; i<args.length; i++) {
			File soundFile;
			//try {
				soundFile = new File(args[i]);
			//} catch (IOException ioe) {
			//	System.err.println("File " + args[i] + " not found");
			//	continue;
			//}
			play(soundFile);
		}
	}

    /**
     * Load and play a specified sound file. If the file is not in a
     * recognised file format, false is returned. Otherwise the sound
     * is started and true is returned. The method returns immediately
     * after the sound starts (not after the sound finishes).
     *
     * @param soundFile  The file to be loaded.
     * @return  True, if the sound file could be loaded, false otherwise.
     */
    public static boolean play(File soundFile)
    {
		int gap = 50;	// ms between plays
        Clip clip = loadSound(soundFile);
        if (clip != null) {
			long microlen = clip.getMicrosecondLength();
            clip.start();
            try {
            	Thread.sleep(microlen/1000 + 1 + gap);
			} catch (Exception e) {}
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * Load the sound file supplied by the parameter into this sound engine.
     *
     * @return  True if successful, false if the file could not be decoded.
     */
    private static Clip loadSound(File file)
    {
        int currentSoundDuration = 0;
        Clip currentSoundClip;

		AudioInputStream stream;

        try {
            stream = AudioSystem.getAudioInputStream(file);
	} catch (Exception ex) {
			System.err.println("File \"" + file + "\" doesn't exist or is broken");
			currentSoundClip = null;
			return null;
	}

	try {
            AudioFormat format = stream.getFormat();

            // we cannot play ALAW/ULAW, so we convert them to PCM
            //
            if ((format.getEncoding() == AudioFormat.Encoding.ULAW) ||
                (format.getEncoding() == AudioFormat.Encoding.ALAW))
            {
                AudioFormat tmp = new AudioFormat(
                                          AudioFormat.Encoding.PCM_SIGNED,
                                          format.getSampleRate(),
                                          format.getSampleSizeInBits() * 2,
                                          format.getChannels(),
                                          format.getFrameSize() * 2,
                                          format.getFrameRate(),
                                          true);
                stream = AudioSystem.getAudioInputStream(tmp, stream);
                format = tmp;
            }
            DataLine.Info info = new DataLine.Info(Clip.class,
                                           stream.getFormat(),
                                           ((int) stream.getFrameLength() *
                                           format.getFrameSize()));
            currentSoundClip = (Clip) AudioSystem.getLine(info);
            currentSoundClip.open(stream);
            int currentSoundFrameLength = (int) stream.getFrameLength();
            currentSoundDuration = (int) (currentSoundClip.getBufferSize() /
                              (currentSoundClip.getFormat().getFrameSize() *
                              currentSoundClip.getFormat().getFrameRate()));
            return currentSoundClip;
        } catch (Exception ex) {
			System.err.println("something did not work: " + ex);
            currentSoundClip = null;
            return null;
        }
    }
}
