Search code examples
javavideovlcj

Closing a video when it ends with VLCJ player?


I'm using VLCJ to play a video when I run my program. Is there any way to close it automatically when the video ends? I wouldn´t a Keylistener to close the video

Thanks!

Code:

String file = "Estopa.mp4";

    public Test(){
        f.setLocation(100,100);
        f.setSize(alto,ancho);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);

        c.setBackground(Color.black);   
        p.setLayout(new BorderLayout());    
        p.add(c);
        f.add(p);

        // Read video file 
        // load native library
        NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(),"C:/Program Files/VideoLAN/VLC");
        Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
        // initialize the media player
        MediaPlayerFactory mpf = new MediaPlayerFactory();
        // control all the interactions with the user
        EmbeddedMediaPlayer emp = mpf.newEmbeddedMediaPlayer(new Win32FullScreenStrategy(f));
        emp.setVideoSurface(mpf.newVideoSurface(c));
        // full screen
        emp.toggleFullScreen();             
        //hide the cursor
        emp.setEnableMouseInputHandling(true);
        //able keyboard
        emp.setEnableKeyInputHandling(true);        
        //prepare file to read
        emp.prepareMedia(file);
        // read the file
        emp.play();



    }

Solution

  • Add a MediaPlayerEventListener to the media player.

    In your listener implementation, add whatever code you want in the finished method.

    Something like this:

    emp.addMediaPlayerEventListener(new MediaPlayerEventAdapter() {
        @Override
        public void finished(MediaPlayer mediaPlayer) {
            System.exit(0);
        }
    });
    

    You might also want to add an implementation for the error callback, since you won't get a finished event if there was an error.

    Note that MediaPlayerEventAdapter is an empty implementation of a MediaPlayerEventListener.