/*
 * 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.sampled.*;

public class OperasiSuara{
    
      private AudioInputStream suara;
      private Clip klip;
      private String namaFile = "";
      private boolean looping = false;
      private int repeat = 0;
      
      public OperasiSuara(){
            try{
                   klip = AudioSystem.getClip();
            }catch(LineUnavailableException e){System.out.println("Terjadi kesalahan pada klip suara : "+e.toString());}
      }
      
      public OperasiSuara(String filesuara) {
            this();//memanggil default konstruktor pertama(tanpa parameter);
            load(filesuara);
      }
      
      public boolean load(String filesuara){
            try{
                   setFilename(filesuara);
                   suara = AudioSystem.getAudioInputStream(getURL(namaFile));
                   klip.open(suara);
                   return true;
            }catch(IOException e){
                   return false;
            }catch(UnsupportedAudioFileException e){
                   return false;
            }catch(LineUnavailableException e){
                   return false;
            }
      }
      
      public void setFilename(String nama_fail) {namaFile = nama_fail;}
      public void setLooping(boolean ulang) {looping = ulang;}
      public void setRepeat(int ulangi) {repeat= ulangi;}
      public Clip getClip() { return klip;}
      public int getRepeat() {return repeat;}
      public boolean getLooping() {return looping;}
      public String getNamaFile() {return namaFile;}
      private URL getURL(String filename){
            URL url = null;
            try {
                   url = this.getClass().getResource(filename);
                   System.out.println(url);
            }catch(Exception e){ System.out.println("error url :"+e.toString());}
            return url;
      }
      public boolean isLoaded(){
            return (boolean)(suara != null);
      }
      
      public void play(){
            if (!isLoaded()) return;
            klip.setFramePosition(0);
            if(looping)
                   klip.loop(Clip.LOOP_CONTINUOUSLY);
            else
                   klip.loop(repeat);
      }
      public void stop(){
            klip.stop();
      }
}

