Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Play/Pause a mp3 file using the JavaZOOM JLayer library?

Tags:

java

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.");
}
like image 305
user2413200 Avatar asked Jun 02 '13 11:06

user2413200


1 Answers

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.

like image 185
Petr Janeček Avatar answered Oct 30 '22 02:10

Petr Janeček