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

后端 未结 1 2033
猫巷女王i
猫巷女王i 2021-02-04 15:46

How would I add a Play/Pause button to the following code?

import javazoom.jl.player.Player;

try{
    FileInputStream fis = new FileInputStream(\"mysong.mp3\");         


        
1条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 16:11

    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.

    0 讨论(0)
提交回复
热议问题