JavaFx MediaPlayer - cannot allocate memory or OutOfMemory

I am building a Java Fx media player and am having a lot of problems to manage my application memory.

The problem is this: when you have a lot of media (video or audio), you need to create a new MediaPlayer every time you need to play a new one.

After some loops, you get an error: Java 7 (OutOfMemory) or Java 8 (mmap () failed: unable to allocate memory).

This is because they don't say anywhere that you need to indirectly call the dispose () method from the last created MediaPlayer before creating a new one.

Link to TIP

+3


source to share


1 answer


Simple and fully functional example:
(This is my small contribution to the community, hope this helps someone)



import java.io.File;

import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class MediaPlayerSample extends Application {

    private File[]      files;
    private int         nextIdx;
    private MediaPlayer activePlayer;

    public static void main(String[] args) {
        launch(args);
    }

    private void playNext() {
        if (files == null || files.length == 0) {
            return;
        }

        Media media = new Media(files[nextIdx++].toURI().toString());
        if (nextIdx >= files.length) {
            nextIdx = 0;
        }

        if (activePlayer != null) {
            activePlayer.stop();
            // This is the magic code
            activePlayer.dispose();
        }

        activePlayer = new MediaPlayer(media);
        activePlayer.setOnEndOfMedia(new Runnable() {
            @Override
            public void run() {
                playNext();
            }
        });

        activePlayer.play();
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        File fDir = new File("/mp3-files/");
        files = fDir.listFiles();
        playNext();
    }

}

      

+4


source







All Articles