11

Here's the code, like the title says the music stops after 10ish seconds, i played the file normally in vlc or other programs, it lasts more than 5 minutes.

public void music(){
        String bip = "src/data/fjordmusic.mp3";
        Media hit = new Media(Paths.get(bip).toUri().toString());
        MediaPlayer mediaPlayer = new MediaPlayer(hit);
        mediaPlayer.play();
    }
user2627736
  • 281
  • 1
  • 4
  • 13
  • This is strange. Can you add more data, like your platform details to the question? – ItachiUchiha May 14 '15 at 06:50
  • Removed duplicate (https://stackoverflow.com/questions/6241687/mediaplayer-stop-playing-after-about-5-seconds ) since even though the solution is the same, the other question asks about android, not javafx... – fabian Apr 24 '19 at 15:16

2 Answers2

20

Your question was already asked and answered here: MediaPlayer stop playing after about 5 seconds

It seems that the garbage collector ereases the MediaPlayer instance after finishing the method. Put the declaration of MediaPlayer above the method and it should work.

MediaPlayer mediaPlayer
public void music(){
    String bip = "src/data/fjordmusic.mp3";
    Media hit = new Media(Paths.get(bip).toUri().toString());
    mediaPlayer = new MediaPlayer(hit);
    mediaPlayer.play();
}

(I'm not able to post comments, so I'm forced to write an answer.)

Community
  • 1
  • 1
Jojo
  • 357
  • 2
  • 10
  • 1
    I actually had to move the entire instantiation outside of the method, not only the declaration. The link you posted actually is not pointing to a JavaFX problem, but it's interesting to observe the same behavior. – LeBird Jun 21 '16 at 08:31
  • I doubt that I would have gotten to the point where I would make the garbage collector responsible for that. You saved me a lot of time! Thanks a lot :) – geisterfurz007 Aug 14 '17 at 06:55
5

Try AudioClip instead:

javafx.scene.media.AudioClip;

    public void music(){
        String bip = "src/data/fjordmusic.mp3";
        Media hit = new Media(Paths.get(bip).toUri().toString());
        AudioClip mediaPlayer = new AudioClip(hit.getSource());
        mediaPlayer.play();
    }
TheBroker
  • 71
  • 3