0

I was trying to make a music application which has a Sound class that extends TimerTask. A class Sound has an Audio Line that repeats the sound with a timer.

My problem came when I was trying to change the rate. It would change the next time the sound starts.

I tried to do something like this:

public class Sound extends TimerTask {

private boolean playing;
private Timer t;
private long rate;


public void turnOn(){

if(!playing){
    playing=true;
    t= new Timer();
    t.scheduleAtFixedRate(this, 0, rate);
}else{
    playing=false;
    t.cancel();
}
}

public void run(){
    if(playing){
        //Here it would play the sound
    }
}
public void changeRate(long rate){
    this.rate=rate;
}

But that does not work. As all I've read I should create a new TimerTask to do the scheduleAtFixedRate, but the TimerTask is the class so, is there any way to make this without creating another Sound class object? Thank you!

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Guille
  • 23
  • 1
  • 6
  • Suggestion: You might want to `ExecutorService` instead of `Timer`. You could say that the `Timer`-class is [more or less deprecated](http://stackoverflow.com/questions/13880202/checking-if-a-java-timer-is-cancelled) (although not officially) – Simon Forsberg Oct 24 '13 at 13:56

1 Answers1

0

If I understand you correctly you probably want an anonymous class:

t.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        if (playing) {
            // play sound
        }
    }
}, 0, rate);

With this Sound does not have to extend TimerTask.