My First Media Player
This tutorial will show you how to build a media player application using very few lines of vlcj code...
Let's Get Started
Start by using the lesson we learnt in the first tutorial, and use the automatic native discovery class to help vlcj find the LibVLC native libraries:
We assume the native libraries can be found like this, if not an exception will be thrown later.
Add a Standard Swing User Interface
Next we create a simple frame, this is totally standard Swing code:
There is nothing particularly special about this code so far, it is all pretty much standard.
If you run this application now you will see an empty grey frame, and that's about it.
Add a Media Player Component
vlcj provides a couple of different ways to create a media player, the simplest
is to use an instance of an
With the few lines of new code we have added here we get a media player
component fully ready to use. The
EmbeddedMediaPlayerComponent is a visual
component that can be added directly to a user interface. In this tutorial we
set the media player component directly as the content pane of the application
frame, we could instead add it to a
JPanel or include it as part of a more
If you run this application now you should no longer see an empty grey frame - you'll see that the frame now contains a media player component (well, all you'll see is that the background changed from grey to black, but the black background is the video surface of the media player component you just added).
We'll now assume that your application accepts the name of a media file to play via a command-line argument:
We've taken some liberties by leaving out argument checking and error handling,
but by adding only one more line of vlcj code,
mediaPlayerComponent.getMediaPlayer().playMedia(args); we have a working
media player. Pretty impressive.
This simple application works just fine, but to help prevent native resource
leaks it is a good idea to explicitly release the media player component when
your application exits. To do this, we don't let the application exit directly
when the close button on the frame is pressed. Instead, we use a
WindowListener to intercept the close event and perform our clean-up:
We changed two things here. The first is we use
EXIT_ON_CLOSE; the second is to add a new window listener that invokes
mediaPlayerComponent.release() to release the media player component and
associated native resources, before exiting the application.
This tutorial has shown how to embed a native media player in a Java application with very few lines of code. This is now the basic template for all vlcj applications.
What's left really is to hook up user interface controls like buttons, menus or keyboard short-cuts to invoke various media player operations, and to listen for and handle media player events.
How you do this is up to you, it depends on the type of application you're building.
The next tutorial shows you the basics of adding controls.