Reputation: 11
I have an application that plays audio files. My problem is that only allows me to pause playback from the position that the music is currently in, but what I want is to pause and continuing playing from that point forward. So far, I could not make that change.
I want to move the slider from another position and be able to play the music from that position on the track.
File juntos = new File("C:/juntos.wav");
if(controlPlay){
//Sliderprogreso is bar Slider
Sliprogreso.setEnabled(true);
controlReproducir=true;
Btngrabar.setEnabled(false);
Btnguardar.setEnabled(false);
Btnplay.setText("Pause");
try {
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
stream = AudioSystem.getAudioInputStream(juntos);
format = stream.getFormat();
frames =stream.getFrameLength();
durationInSeconds = (frames+0.0) / format.getFrameRate();
System.out.println("duracion:"+durationInSeconds);
Sliprogreso.setMaximum((int) durationInSeconds);
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
controlPlay=false;
TimerTask timerTask=new TimerTask(){
public synchronized void run() {
{
double timeNow=(durationInSeconds*clip.getFramePosition())/frames;
System.out.println("frames:"+frames);
System.out.println("clipframe:"+clip.getFramePosition());
System.out.println("time now");
Sliprogreso.setValue((int)Math.round(timeNow));
if((int)Math.round(timeNow)==(int)durationInSeconds){
System.out.println("se cancelo");
this.cancel();
Btnplay.setText("Play");
Btngrabar.setEnabled(true);
Btnguardar.setEnabled(true);
controlPlay=true;
}
}
}
};
timer.scheduleAtFixedRate(timerTask, 30, 30);
}
catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
}
else{
clip.stop();
timer.cancel();
Btnplay.setText("Play");
controlPlay=true;
Btngrabar.setEnabled(true);
Btnguardar.setEnabled(true);
}
Upvotes: 0
Views: 326
Reputation: 7910
Have you looked at the Clip API? There are methods for pausing and for setting the "playhead" to any position, using either frames or elapsed time.
From within your TimerTask:
if (positionOnSliderUpdatedByUser)
{
clip.stop();
int desiredMicrosecond = yourConversionFunction( sliprogreso.getValue() );
clip.setMicrosecondPosition(desiredMicrosecond);
clip.start();
positionOnSliderUpdatedByUser = false;
}
I'm not sure if I am reading your code correctly, especially with your lack of formatting. I'm taking it that you are updating the slider regularly with the song position, but that if the user changes the slider, then you want to move to that point in the song. Thus, there should be some sort of process to flag when the user changes the slider (as opposed to the song changing the slider). I'm using the flag name "positionOnSliderUpdatedByUser".
Upvotes: 1