[A]How to make a MP3 repeat in javafx?

2020-03-02 04:33发布

问题:

i want my mp3 file repeat again after it finished . but i'm unable to create a loop to play my file repeatedly (i used this code but only it plays first second of my file after it finished)

AudioClip myMusic ....   
myMusic.setCycleCount(AudioClip.INDEFINITE);
myMusic.play();

Edited : i used MediaPlayer but it's cycle counter didn't work correctly for example first time i played my mp3 file it played 2 times and in 3rd time of playing suddenly it stops second time i ran again my app and it played 1 time and in half of second time of playing it stops here is my code :

URL resource = getClass().getResource("abcd.mp3");
     MediaPlayer a =new MediaPlayer(new Media(resource.toString()));
     a.setCycleCount(MediaPlayer.INDEFINITE);

 a.play();

any ideas?thanks in advance .

回答1:

i found my solution i used setOnEndOfMedia method :

 URL resource = getClass().getResource("abcd.mp3");
 MediaPlayer a =new MediaPlayer(new Media(resource.toString()));
 a.setOnEndOfMedia(new Runnable() {
       public void run() {
         a.seek(Duration.ZERO);
       }
   });
  a.play();


回答2:

for avoiding the suddenly stopping, you must :

a.setOnReady(new Runnable() {
        @Override
        public void run() {
            a.play();
        }
    });

It works for me.



标签: javafx