简体   繁体   English

如何使用JavaZOOM JLayer库播放/暂停mp3文件?

[英]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. 你需要使用AdvancedPlayer类而不仅仅是Player ,因为更简单的类不能真正开始在中间播放文件。

You'll need to add a PlaybackListener and listen for the stop() method. 您需要添加一个PlaybackListener并监听stop()方法。 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) . 现在,当暂停后再次按下Play时,您将检查pausedOnFrame是否是介于0和文件中帧数之间的数字并调用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. 也就是说,API在您的情况下似乎没有什么帮助,但除了切换到不同的库之外,它是您可以做的最好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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