Search code examples
vlcvlcj

Capturing with vlcj only gives a corrupt video file


I am using vlcj to capture the screen in my Java program. Therefore I use the following code:

public static void main(final String[] args) {
            NativeLibrary.addSearchPath("vlc", "/Applications/VLC.app/Contents/MacOS/lib/");
            SwingUtilities.invokeLater(new Runnable() {
              @Override
              public void run() {
                new CaptureTest().start("screen://");
              }
            });
          }

public CaptureTest() {
            factory = new MediaPlayerFactory();
            mediaPlayer = (HeadlessMediaPlayer) factory.newMediaPlayer();
          }

          private void start(String mrl) {

            File dir = new File(System.getProperty("user.home"), "Videos");
            dir.mkdirs();

            DateFormat df = new SimpleDateFormat("yyyyMMdd-HHmmss");
            String fileName =  dir.getAbsolutePath() + "/Capture-" + df.format(new Date()) + ".mp4";

            String[] options = {
            ":sout=#transcode{vcodec=h264,acodec=mp4a}:std{mux=mp4,access=file,dst=" + fileName + "}", ":input-slave=screen://"
            };

            mediaPlayer.playMedia(mrl, options);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mediaPlayer.stop();
            mediaPlayer.release(); 
          }

The problem is that the video output file is only 4KB and you can't play it. Can anyone help me? I am on Mac OS 10.6.8 and I use VLC 1.1.12 and vlcj 1.1.5


Solution

  • Here is the interesting part of your code...

        mediaPlayer.playMedia(mrl, options);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        mediaPlayer.stop();
        mediaPlayer.release(); 
    

    Why did you play the media, slept for 5 seconds and stopped immediately after that? Maybe, this is why you get a very small file size during the screen recording. From what I notice, the transcode is not so fast enough, so the file is not increasing in size immediately (maybe due to buffering takes place during transcoding part, I guess...)

    The best is to create a button each for the play/record action and for the stop action.