/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/**
 *
 * @author dhafiq
 */

import java.io.*;
import java.net.*;
import javax.sound.midi.*;

public class OperasiMidi{
      private Sequence suara;
      private Sequencer ambilSuara;
      private String namaFile;
      private boolean looping = false;
      private int repeat = 0;
      public OperasiMidi(){
            try{
                   ambilSuara = MidiSystem.getSequencer();
            }catch(MidiUnavailableException e){ }
      }
      public OperasiMidi(String fileMidi){
            this();                   //memanggil default konstruktor pertama(tanpa parameter);
            load(fileMidi);
      }
      public boolean load(String fileMidi){
            try{
                   namaFile = fileMidi;
                   suara = MidiSystem.getSequence(getURL(namaFile));
                   ambilSuara.setSequence(suara);
                   ambilSuara.open();
                   return true;
            }catch(InvalidMidiDataException e){
                   return false;
            }catch(MidiUnavailableException e){
                   return false;
            }catch(IOException e){
                   return false;
            }
      }
      public void setLooping(boolean ulang) {looping =ulang;}
      public void setRepeat(int ulangi) {repeat= ulangi;}
      public Sequence getSuara() { return suara;}
      public String getFilename() {return namaFile;}
      public boolean getLooping() {return looping;}
      public int getRepeat() {return repeat;}
      private URL getURL(String filename){
            URL url = null;
            try {
               url = this.getClass().getResource(filename);
        }catch(Exception e){ }
        return url;
  }
  public boolean isLoaded(){
        return (boolean)(ambilSuara.isOpen());
  }
  public void play(){
        if(!ambilSuara.isOpen()) return;
        if(looping){
               ambilSuara.setLoopCount(Sequencer.LOOP_CONTINUOUSLY);
               ambilSuara.start();
        }else{
               ambilSuara.setLoopCount(repeat);
               ambilSuara.start();
        }
  }
  public void stop(){
        ambilSuara.stop();
  }
}

