Been testing a new system for increasing/decreasing the audio within my JavaSwing application using a fade in and fade out effect. This works on one hand though by doing my own research, it's not as optimal as one hoped to be since it utilizes Thread.sleep(x);
rather than using Timer();
from JavaSwing.
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
value = (value <= 0.0) ? 0.0001 : ((value > 1.0) ? 1.0 : value);
try {
float db = (float) (Math.log(percent) / Math.log(10.0) * 20.0);
gainControl.setValue(db);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void shiftVolumeTo(double value) {
value = (value <= 0.0) ? 0.0001 : ((value > 1.0) ? 1.0 : value);
targetDB = (float)(Math.log(value)/Math.log(10.0)*20.0);
if (!fading) {
Thread t = new Thread();
t.start();
}
}
public static void run() {
FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
fading = true;
if(currDB > targetDB) {
while (currDB > targetDB) {
currDB -= fadePerStep;
gainControl.setValue(currDB);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else if (currDB < targetDB) {
while(currDB < targetDB) {
currDB += fadePerStep;
gainControl.setValue(currDB);
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
fading = false;
currDB = targetDB;
}
public static void volTest() {
setVolume(1);
shiftVolumeTo(.2);
run();
}
Again, this works properly when run();
is called, but it puts the entire application to sleep within the duration of the while
loop's runtime. Which is what I'm having an issue with. I've tried setting up a JavaSwing Timer();
within the code though I couldn't figure out how to set it up properly to make the delay run like the Thread.sleep(x);
method. Whether it is adding the code from run();
into the ActionListener
created or utilized by the timer or just having run();
within the ActionListener
. Unlike Thread.sleep(x);
, the program will just jump values without taking it's time to decrease the volume as there's no delay between the incremental increase/decrease of the while
loop.
What would be the optimal way to utilize a JavaSwing Timer();
that would work similar to a Thread.sleep(x);
in this situation?