Monday, December 2, 2013

Play Media Files With VLCJ in Java

Hello, today I will teach you how to work with your media files like video or music formats.
There is JMF in Java but it seems to be outdated and very old so some people who works on an open source projects started to develop and port the famous VLC library from C++ called vlcj.
It is currently being hosted on Google Code and they're updating it from time to time.

I will show you a quick example on how to use this wonderful library. Just copy and paste this code to your favorite IDE like Eclipse. Note that you should first need to download the library and add it to your project classpath.


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;

import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;

    public class VideoExample {

        private final EmbeddedMediaPlayerComponent mediaPlayerComponent;

        public static void main(final String[] args) {
         NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "C:\\Program Files\\VideoLAN\\VLC");
         Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new VideoExample(args);
                }
            });
        }

        private VideoExample(String[] args) {
            JFrame frame = new JFrame("vlcj Tutorial");

            mediaPlayerComponent = new EmbeddedMediaPlayerComponent();

            frame.setContentPane(mediaPlayerComponent);

            frame.setLocation(100, 100);
            frame.setSize(500, 500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);

            mediaPlayerComponent.getMediaPlayer().playMedia("D:\\video.avi");
            
        }
    }
Output:

Voila! With just a few lines of code, you may have your own media player like this. You can now start to explore more tutorials on Google and start to read the library's documentation online of offline to develop your own program that suite to your own needs.
Thanks for reading!

4 comments:

  1. i tried above code but getting error as
    Error:(20, 9) java: cannot find symbol
    symbol: variable NativeLibrary
    location: class javaapplication3.test.VideoExample
    and
    Error:(21, 9) java: cannot find symbol
    symbol: variable Native
    location: class javaapplication3.test.VideoExample
    what could be the possible errors? Thanks in advance.

    ReplyDelete
  2. Hello there!

    Have you setup properly your Eclipse library? Seems like you have not yet. Let me know in what way I can help.

    Thanks!

    ReplyDelete