Rodrigo Tavares
Rodrigo Tavares

Reputation: 369

JavaFx MediaPlayer - Cannot allocate memory or OutOfMemory

I'm creating a Java Fx Media Player and I've been having a lot of problems to manage the application memory.

The problem is: When you have to many medias (video or audio) , you have to create a new MediaPlayer every time you have to play new one.

After some loopings you will get an error: Java 7 (OutOfMemory) or Java 8 (mmap() failed: Cannot allocate memory).

This happens because nowhere they say that you have to implicit call the dispose() method from the last created MediaPlayer before you create a new one.

TIP Reference

Upvotes: 2

Views: 928

Answers (1)

Rodrigo Tavares
Rodrigo Tavares

Reputation: 369

A simple and fully functional example:
(This is my small contribution with 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();
    }

}

Upvotes: 3

Related Questions