import java.io.*;
import java.net.URL;
import java.util.*;
import javax.sound.sampled.*;

/*
* Play .wav audio files
*
*to use
*	import javax.sound.sampled.*; 
* 	public AudioWrapper <name> = new AudioWrapper(); 
*
*	try	
*	{
*	    <name>.load(<soundfile>);
*	}
*	catch Exception e{}
*
*	try 
*	{
*		<name>.play();
*		<name>.loop();
*	} 
*	catch (UnsupportedAudioFileException e1) 
*	{
*		 e1.printStackTrace();
*	} 
*	catch (LineUnavailableException e1) 
*	{
*		e1.printStackTrace();
*	}

*/




public class AudioWrapper  {
      private AudioFormat af;
      private int size;
      private DataLine.Info info;
      private byte[] data;
      // int size = data.length;
      private Clip clip;

      public AudioWrapper() { }

      public void play() throws UnsupportedAudioFileException, LineUnavailableException {
         //if (clip != null)
            //stop();
            
         clip = (Clip)AudioSystem.getLine(info);
         clip.open(af, data, 0, data.length);
         clip.start();

          //clip.start();
          //clip.loop(Clip.LOOP_CONTINUOUSLY);
      }
      public void loop() throws UnsupportedAudioFileException, LineUnavailableException {
         //if (clip != null)
            //stop();
            
         clip = (Clip)AudioSystem.getLine(info);
         clip.open(af, data, 0, data.length);
         clip.start();
         clip.loop(Clip.LOOP_CONTINUOUSLY);
      }

      public void stop() throws UnsupportedAudioFileException, LineUnavailableException {
         if (clip != null)
           clip.stop();
         clip = null;         
      }

   public void load(String fileName) throws Exception {
      // dispose previous clip if was loaded
      try { if (clip != null) clip.stop(); } catch (Exception ex) { }
      this.af  = null;
      this.info = null;
      this.data = null;
      this.clip = null;

      // We read all bytes to ByteInputStream first then use it
      // as a source stream. We probably could stream directly
      // from files but then must use FIS opened for longer time.
      // TODO: change to URL-stream to support file+jar+web sources (see previous example)
      FileInputStream fis = new FileInputStream(fileName);
      InputStream is = loadStream(fis);
      AudioInputStream ais = AudioSystem.getAudioInputStream(is);
      fis.close();

      this.af   = ais.getFormat();
      int size = (int)(this.af.getFrameSize() * ais.getFrameLength());
      this.info = new DataLine.Info(Clip.class, this.af, size);
      this.data = new byte[size];
      ais.read(this.data, 0, this.data.length);
   }

   // load inputstream to ByteArrayInputStream
   private ByteArrayInputStream loadStream(InputStream is) throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      byte data[] = new byte[1024];
      for(int i = is.read(data); i != -1; i = is.read(data))
         baos.write(data, 0, i);
      baos.close();
      return new ByteArrayInputStream(baos.toByteArray());
  }
}