8

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.");
}
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
user2413200
  • 245
  • 3
  • 7
  • 12
  • This thread should help you, it covers everything pretty nicely : http://stackoverflow.com/questions/6045384/playing-mp3-and-wav-in-java – Stanimirovv Jun 02 '13 at 11:37
  • use MediaPlayer class – Dejan Jun 02 '13 at 11:47
  • 6
    I seriously don't know why this question was closed. I know the answer and I was just typing it in. OP's not using the usual JMF and is asking a pretty straightforward question which has an answer that may not be obvious on the first sight. Sure, it's not the most well-behaved question of all time, but it makes sense to me. – Petr Janeček Jun 02 '13 at 12:01
  • 1
    @Slanec It's re-opened if you want to type said answer in. – Patashu Jun 03 '13 at 03:54
  • @user2413200 Did the Integer.MAX_VALUE trick work? – Petr Janeček Jun 05 '13 at 13:12

1 Answers1

10

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.

Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 2
    The play() method of AdvancedPlayer is internally using Integer.MAX_VALUE too, so it should be fine. I took quick look at the implementation. – Ivo Feb 27 '14 at 23:36
  • 5
    I've tried to implements this too, but at resuming i got a random point access to track..., i've checked the event.getFrame(), it seems the value passed is not corresponding to what we're listening... – Black.Jack Dec 17 '14 at 14:22