简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM