/***************************************************
  Author: Sasha Devore
  Date: 12/10/97
  Applet: Metronome, a self-animating, auditory metronome

  Please do not modify this code in any way
  
  *************************************************/

import java.awt.*;
import java.applet.*;
import java.lang.*;


/******************************************************
  Class: Metronome
  Instance: Each instance of class Metronome is a self-animating
  metronome applet
  ****************************************************/

public class Metronome extends Applet implements Runnable 
{
  
    //fields
    private AudioClip ClickSound; //the sound file
    private Thread runner;        //the animator
    private Button start, stop;  //the two buttons
    private Scrollbar TickTime;  //the scrollbar
    private TextField tf1; //the text field where the bpm appears
    private int tempo;  //the current tempo
    private boolean play = false;  


    //this method initializes all of the components
    
	public void init() {
		this.setBackground(Color.white);
		
		start = new Button("Start");
		stop = new Button("Stop");
		TickTime = new Scrollbar(Scrollbar.HORIZONTAL, 0,1, 30, 180);
		tf1 = new TextField("blah",3);

	       
		this.add(TickTime);
		this.add(tf1);
		this.add(start);
		this.add(stop);

		ClickSound = getAudioClip(getCodeBase(), "ClickSound.au");
	}

    //the action method handles the buttons presses
    
	public boolean action(Event e, Object arg) {
	    	if(e.target == start) {
			play = true;
			
		} else if(e.target == stop) {
			play = false;
			
		}
                return true;		    
	}	


    //the start method (called when the applet is called)
     public void start()
        {      
		if (runner == null)
                {       runner = new Thread( this); 
                        runner.start() ;            
                }
        }

    //stop() called when the browser stops or destroys
	public void stop()
        {
	   if(runner != null)
           {
	       runner.stop();
               runner = null;
           }
        }
       
    //run() is the animacy, always checking to see if it should
    //play
        public void run ()
        {   
            while(true) {
		tempo = this.TickTime.getValue();
		String s=String.valueOf(tempo);
		tf1.setText(s);
	        if (play) {
	            PlayMetro();
	        }
           }
	}

    //the PlayMetro() method is what makes the sound play
public void PlayMetro( )
{
   
	tempo = 60*1000/tempo;   //convert to correct time
 
        ClickSound.play();
        try{Thread.sleep(tempo);} catch(InterruptedException e){}
	
}

}


