user2627736
user2627736

Reputation: 301

JavaFX MediaPlayer - Music stops after 10 seconds

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();
    }

Upvotes: 12

Views: 10105

Answers (2)

Rummel
Rummel

Reputation: 437

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.)

Upvotes: 25

TheBroker
TheBroker

Reputation: 71

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();
    }

Upvotes: 5

Related Questions