How would I add a Play/Pause button to the following code?
import javazoom.jl.player.Player;
try{
FileInputStream fis = new FileInputStream("mysong.mp3");
Player playMP3 = new Player(fis);
playMP3.play();
}
catch(Exception exc){
exc.printStackTrace();
System.out.println("Failed to play the file.");
}
You'll need to use the AdvancedPlayer class instead of just Player, because the simpler one can't really start playing the file in the middle.
You'll need to add a PlaybackListener and listen for the stop() method. Then you can simply start again from the moment you left off.
private int pausedOnFrame = 0;
AdvancedPlayer player = new AdvancedPlayer(fis);
player.setPlayBackListener(new PlaybackListener() {
@Override
public void playbackFinished(PlaybackEvent event) {
pausedOnFrame = event.getFrame();
}
});
player.play();
// or player.play(pausedOnFrame, Integer.MAX_VALUE);
This will remember the frame playing was paused on (if paused).
And now, when Play is pressed again after a pause, you'll check whether pausedOnFrame is a number between 0 and the number of frames in the file and invoke play(int begin, int end).
Note that you should know the number of frames in the file before you do this. If you don't, you could try to play all the frames via this trick:
player.play(pausedOnFrame, Integer.MAX_VALUE);
That said, the API doesn't seem very helpful in your case, but it's the best you can do other than swiching to a different library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With