How to play audio and video files in Java applications

Introduction

In this post I’m going to show you how to play an audio and a video file using a java application. At first I have to mention that I’m using Java Media Framework (JMF) for this purpose. So you have to download and install JMF from here. According to the web page you can,

  • Playback audios and videos
  • Capture from devices
  • Transmitt over an internet connection

JMF is providing you necessary classes and you have to do less. But in here I’ve to mention that JMF is a bit old too. In many cases you won’t be able to play every media file you want. Because there are some restrictions. Through following examples I’ll show you how to get the use of JMF.

Creating an audio player

Before going to build an audio player you have to be familier with the classes and their methods that are going to use.

Player: As the name says Player is responsible for playing the given file. It has start(), stop(), close() methods. Player also have number of states too.

  • Prefetched
  • Prefetching
  • Realized
  • Realizing
  • Started
  • Unrealized

Manager: Manager is responsible for creating appropriate player object using an URL or a Media Locator.  Manager is also use to create a processor – will be explained later.

SimpleAudioPlayer.java

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.media.*;   // import JMF classes
import javax.swing.JFileChooser;

/**
*
* @author BUDDHIMA
*/

public class SimpleAudioPlayer {

private Player audioPlayer = null;

public SimpleAudioPlayer(URL url) {

try {

//MediaLocator ml=new MediaLocator(url);

audioPlayer = Manager.createPlayer(url);

} catch (Exception ex) {

System.out.println(ex);

}

}

public SimpleAudioPlayer(File file) throws MalformedURLException {

this(file.toURI().toURL());

}

public void play() {

audioPlayer.start(); // start playing

}

public void stop() {

audioPlayer.stop();  //stop playing

audioPlayer.close();

}

public static void main(String[] args) {

try {

// TODO code application logic here

JFileChooser fc = new JFileChooser();

fc.showOpenDialog(null);

File file = fc.getSelectedFile();

SimpleAduioPlayer sap = new SimpleAduioPlayer(file);

sap.play();

//sap.stop();

} catch (MalformedURLException ex) {

System.out.println(ex);

}

}

}

With this example you can play MP3, WAV, and AU files.

Creating a video player

Not like audio player, Video player deals with GUI. Therefore you should have a little knowledge about Swing components. In addition to previous things you have to get Visual component and Control Panel component from the Player instance created by you. Then you have to place those in a necessary Swing component (here JPanel is used).

MediaPlayer.java


import java.awt.BorderLayout;
import java.awt.Component;
import java.net.MalformedURLException;
import java.net.URL;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/**
*
* @author BUDDHIMA
*/

public class MediaPlayer extends javax.swing.JPanel {

public MediaPlayer(URL mediauUrl) {

initComponents();

setLayout(new BorderLayout());

try {

Player mediaPlayer=Manager.createRealizedPlayer(new MediaLocator(mediauUrl));

Component video=mediaPlayer.getVisualComponent();

Component control=mediaPlayer.getControlPanelComponent();

if (video!=null) {

add(video, BorderLayout.CENTER);          // place the video component in the panel

}

add(control, BorderLayout.SOUTH);            // place the control in  panel

mediaPlayer.start();

} catch (Exception e) {

}

}

public static void main(String[] args) {

JFileChooser fileChooser = new JFileChooser();

fileChooser.showOpenDialog(null);

URL mediaUrl=null;

try {

mediaUrl = fileChooser.getSelectedFile().toURI().toURL();

} catch (MalformedURLException ex) {

System.out.println(ex);

}

JFrame mediaTest = new JFrame( "Movie Player" );

mediaTest.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

MediaPlayer mediaPanel = new MediaPlayer( mediaUrl );

mediaTest.add( mediaPanel );

mediaTest.setSize( 800, 700 ); // set the size of the player

mediaTest.setLocationRelativeTo(null);

mediaTest.setVisible( true );

}

}

When you run this code and select a file, you would get something like this. But you can only play limited number of video fromats only (.mpg, some .avi files). Give a try ! 😀

Willing to tell more intractive activities using JMF  ………

Resources:

  1. JMF official site : http://www.oracle.com/technetwork/java/javase/tech/index-jsp-140239.html
  2. JMF examples : http://blogs.sun.com/geertjan/date/20070121
Advertisements

99 thoughts on “How to play audio and video files in Java applications

      1. Hey I need help on how to read and save a video file just like in images I used buffered reader. please I need help on that as it is very urgent.

  1. hey please I also have problem in the video but the audio works will here is what I am experiencing (Exception in thread “main” java.lang.Error: Unresolved compilation problem:
    The method initComponents() is undefined for the type MediaPlayer

    at MediaPlayer.(MediaPlayer.java:16)
    at MediaPlayer.main(MediaPlayer.java:66)
    )

  2. simple question…………..how do i add jmf to the eclipse or the package to run your codes. i have downloaded jmf and installed it…but dont know how to use it. Your code doesnt work when i write them in eclipse as it dont have javax.media

      1. hiiii,,
        can u little ellaborate about jmf for running video file…….we have to install jmf or plugin?

      2. Hi Satish,
        For the application to run a video file, you need to install JMF in your PC. Link to download it is provided in the article.
        Then you need to add the libraries in that JMF to the project libraries. After that you will be able to import “javax.media.*;”.
        There’s no plugin involved in this process.
        Hope this small guidance will help you 🙂

  3. please help me i have a project to transmit audio and video via LAN using java can you help me to give a code ???
    Thanks!!!!

  4. hey..
    import javax.media.Manager;
    import javax.media.MediaLocator;
    import javax.media.Player;

    javax is not found. why? can you help?

    1. Hi Gani,
      You can have a better understanding on formats that JMF supports through this:
      http://www.oracle.com/technetwork/java/javase/formats-138492.html

      You may need to convert your video in to a format that JMF support or you have to integrate following plugin to the JMF framework
      http://jffmpeg.sourceforge.net/

      According to documents it should support xvid format
      http://jffmpeg.sourceforge.net/formats.html

      Hope you get the solution 🙂

  5. hi..
    when i run the code i got the following Exception

    Unable to handle format: mpeglayer3, 44100.0 Hz, 16-bit, Stereo, LittleEndian, Signed, 16000.0 frame rate, FrameSize=32768 bits
    Failed to realize: com.sun.media.PlaybackEngine@6ab7501b
    Error: Unable to realize com.sun.media.PlaybackEngine@6ab7501b

  6. Hi,
    Can you please help me with simply storing a video file over a web service and it being downloaded or played by the client in java. Thanks in advance.

  7. help pls and pls i’m a student in Adamawa State University, Mubi Adamawa State, Nigeria, West Africa force to write a Project On JAVA multimedia Player using JAVA Media Framework(jmf). help pls I DON’t KNOW HOW TO GO ABOUT IT EVEN program using JAVA

    1. Hi Mivanyi,
      First you must find someone who familiar with Java and Netbeans (or any-other) IDE. ( since I’ll not be available with in next few days).
      First you need to create a JAVA project and import JMF jars.
      Then copy paste MediaPlayer code to a newly created file named MediaPlayer.java.

      If you need more help, feel free to contact 🙂

    1. Hi Atul,
      Thanks !!!
      I haven’t worked with JDeveloper IDE yet. But it seems to be the main development platform for the Oracle Fusion Middleware suite of products (main difference compared to other IDEs). You can find more through following links.
      1. http://www.oracle.com/technetwork/developer-tools/jdev/overview/index.html
      2. http://docs.oracle.com/cd/E18941_01/tutorials/toc.htm
      3. http://docs.oracle.com/cd/E16162_01/user.1112/e17455/working_jdev.htm

  8. Hi, thank you for your post.

    But the method initComponents is not defined.

    Moreover, some lines are wrong according to the package mediaplayer.
    The line “MediaPlayer mediaPanel = new MediaPlayer( mediaUrl );” must be replaced by:
    MediaPlayer mediaPanel = new MediaPlayer();
    mediaPanel.setCodeBase(mediaUrl) ;

    Is that really work for you?

    1. Hi Guillaume,
      This example is working. It seems like you have a confusion with the code.
      initComponents(); method is an auto generated method by IDE(in here Netbeans) to to call initComponents() in JPanel (the super class of MediaPlayer).
      In here MediaPlayer is not referring external class. It refers the MediaPlayer class in the sample code. So you can see that constructor of MediaPlayer class in here takes a URL.
      Hope the explanation will help to solve your confusion 🙂

  9. i am facing a problem in video player
    Exception in thread “main” java.lang.UnsupportedOperationException: Not yet implemented
    at videoplayer.VideoPlayer.initComponents(VideoPlayer.java:85)
    at videoplayer.VideoPlayer.(VideoPlayer.java:22)
    at videoplayer.VideoPlayer.main(VideoPlayer.java:72)
    Java Result: 1
    please solve my problem…..

    1. Hi Mohit,
      I used Netbeans to create this program. So “initComponents()” is a method which is auto generated to initialize components in the frame. If you are using another IDE you need to call appropriate methods which does the same thing.
      🙂

  10. Thank u…
    I am studying Computer Science & Engineering in Dr. SACOE.
    I have run mediaplayer.java. but i have this error how to clear it….Pls reply me friend….

    Unable to handle format: H264, 640×360, FrameRate=25.0, Length=691200 0 extra
    bytes
    Unable to handle format: mpeglayer3, 44100.0 Hz, 0-bit, Stereo, Unsigned, 3200
    0.0 frame rate, FrameSize=9216 bits
    Failed to realize: com.sun.media.PlaybackEngine@3ae941
    Error: Unable to realize com.sun.media.PlaybackEngine@3ae941
    Press any key to continue…

    1. Hi Muthu,
      I’m so glad to hear that you are also an Computer Science and Engineering undergraduate. 🙂
      It seems like the problem is with the file type you are going to ply in this media player. This player can only play few types of media files (mpg and some avi files).
      So can you try on such files and let me know the result?
      Thanks !

  11. How I can play streaming video at my system player in full screen. I have URL and I need run some system media player in full screen. Is it possible?

    Thanks

  12. my project go well ma….. very thanks to help me….. then another doubt how to capture audio from a particular place using microphone and send it to server in every 15 min……

    1. Hi Muthu,
      Hope you can do capturing part through a looping process. To capture sound Java Sound API may be more suitable.
      http://www.java2s.com/Tutorial/Java/0120__Development/CapturingAudiowithJavaSoundAPI.htm

      To send files following links may help you. Actually they show how to send a file from server-to-client. But after get the concept, reverse of that can be applied to your project too.
      http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and-server-using-java-socket
      http://www.rgagnon.com/javadetails/java-0542.html
      Btw, what king of application are you creating? is the server is a file server (using FTP) ? Techniques may differ depending your application.
      Thanks !

  13. Hi Buddhima,
    I try that code is run very well..
    but how to implements that code in jframe (from main class which must changes) and not open directories like that??
    and also i try to make my sound looping but failed..

    1. Hi,
      This code uses a JFrame (you can see it in main method). What you are going to do is not clear.
      You can cancel JFileChooser, but you need to provide a URL of media inside your code or somehow.
      Thank You !

  14. i have written the codes at 2 places but none seems to work
    1. netbeans : i wrote the entire code in netbeans for audio and included d jmf library as you told you ,…the program is complex. no errors.. but certainly i am not able to see any output …. nothing is being displayed.. whats the problem??

    2. texteditor : wrote the code in text editor.. compiled it.. but getting error with media package.. i saved my java file in d same jmf/bin but still there is an error.

    please help me out…. i have a macbook pro…. !

  15. formats only (.mpg, some .avi files). Any library to play video format like mp4,flv and etc? i need idea for this..
    thx before

      1. thx u buddhima.. hmm i still confuse use vlcj, do you have tutorial for this? and JMF can intregation with vlcj? sorry i’am newbie in programming >,<

  16. Dear sir
    I am working on web project using servlet and jsp … i need a media player for that using java…so please help me for this…… i need code for player so that i can run hat code on my web pages…..the player are totally based on java…
    So please help me to doing this

    Thank you

    Your Code was Really really good 🙂

    please help me to doing my task

  17. Hi,

    I am getting like this error,

    “Unable to handle format: MPEG, 352×240, FrameRate=29.9, Length=126720”

    can not see the video but getting sound while running this

  18. Hi and thank you for this very clear example of code.

    I’m working on a project management advertising screens. Currently, the solution is on a Net Platform, but we need a more lightweight solution for deployment (screens often have an embedded version of Windows on which the .Net framework can not be installed). So I thought of using Java for portability, but the limitation in terms of video formats is a real problem.
    Do you think there is another library that can handle a variety of formats? I’ll try vlcj library as you now recommend, hoping it can meet my need for movies. Unfortunately, I think there is not a lot of sample code ……

    But, I also flash videos to integrate this program. You would know a library capable of playing flash videos?

    Congratulations again for this article.

  19. need your help for my school project. I need to play music when play button is clicked. I tried to import the javax.media.* but it shows error that package does not exist even when I have imported d package :/ please help.!!

    1. Hi Maya,
      It seems you haven’t add JMF as a library to NetBeans project.
      For that first you have to right click on the project name on the projects window. Click “Properties” from the pop-up you get. Go to “Libraries” section. Click “Add Jar/Folder” and select the “jmf.jar” from the location where you install the JMF.
      Hope you will be able to solve the problem.
      Thank You!

  20. Hi, good work. I have a question. I copied your Code and added all jars from JMF in my Project, but he cant do initComponents() and Mediaplayer mediaplayer = new MediaPlayer( mediaUrl ); Can you help me out. I want to have a videoplayer example that works so I can look at it when I am trying to write my own player

  21. Nice post…
    and I have a question i have made a audio media player app using JMF going through ur example bt when i have made a JAR the mp3 is not playing. i am using netbeans, can u say what may be the reason?

    1. Hi Prabir,
      I’m not clear about your issue. Is that mp3 song played when running source code in Netbeans ? If so, you may need to rebuild the jar file.
      Else, JMF may not support that particular type of mp3 file.
      Thanks!

      1. when i am running source code then the mp3 song is palying and to play mp3 in jmf i have used mp3plugin.jar but when i make Jar file then audio is not playing…

  22. hi,

    I want to develop a UI which can show the video/image through web cam and can also capture them. Is there any way can you help me out? Please reply.

    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s