Playing an AVI file using Java code

Looking for someone to post some sample code on how to play an AVI file through Java.  The avi file i want to play will be local to the users machine, this is why i should use java instead of asp.

any help on this subject would be great.
 
LVL 1
jtjcompAsked:
Who is Participating?
 
ovidiucraciunConnect With a Mentor Commented:
Wav-files are easy.
If you're using an applet, just say


 
myAudioClip = myApplet.getAudioClip("http://some.url/name.wav");
myAudioClip.play();

With Java 2 there's some way to do this in an application too, but I'm not sure how...

AVI:s are harder, you have to dowload the Java Media Framework standard extension. This package can play (and very closely control and synchronize) MPEG-1, MPEG-2, QuickTime, AVI, WAV, AU, MIDI and more.

The code would go something like this:


 
   ...
   ControllerListener cl=new ControllerListener() {
      public synchronized void controllerUpdate(
                              ControllerEvent event) {
         if (event instanceof RealizeCompleteEvent) {
            Component comp;
            if ((comp = player.getVisualComponent()) != null) {
               myApplet.add ("Center", comp);           
               validate();
            }
         }
      }
   };
   ...
   URL mediaURL = new URL("http://some.url/name.avi");
   player = Manager.createPlayer(mediaURL);
   player.addControllerListener(cl);
   player.start();

For more examples, check this link out.

http://java.sun.com/products/java-media/jmf/forDevelopers/playerguide/index.html
0
 
heyhey_Commented:
applet ? application ?
0
 
jtjcompAuthor Commented:
applet
0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
ovidiucraciunCommented:
just sign for further responses ;)
0
 
jtjcompAuthor Commented:
Is this a question that can not be answered, I'm I going about the task with the wrong langauge.
0
 
conickCommented:
It can be answered.  However, I'm not sure what kind of power you have over the client side user.
For instance to look at files on the client side you need a "signed" applet for security purposes.
Also to play an AVI in an applet/application you need an extension called JMF (Java Media Framework) plugged in.

Given all these issues are taken care of you can use the following code.
This code was taken from the java.sun.com site (the jmf section).  You would have to modify how to select what file to play.
//TypicalPlayerApplet.java
import java.applet.Applet;
import java.awt.*;
import java.lang.String;
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;
import javax.media.*;
/**
* This is a Java Applet that demonstrates how to create a simple
* media player with a media event listener. It will play the
* media clip right away and continuously loop.
*
* <!-- Sample HTML
* <applet code=TypicalPlayerApplet width=800 height=500>
* <param name=file value="indeotst.avi">
* </applet>
* -->
*/
public class TypicalPlayerApplet extends Applet implements ControllerListener  {
     // media player
     Player player = null;

     // component in which video is playing
     Component visualComponent = null;
     // controls gain, position, start, stop
     Component controlComponent = null;
     // displays progress during download
     Component progressBar = null;
     
     /**
     * Read the applet file parameter and create the media
     * player.
     */
     
     public void init()  {
          setLayout(new BorderLayout());
          // input file name from html param
          String mediaFile = null;
          // URL for our media file
          URL url = null;
          // URL for doc containing applet
          URL codeBase = getDocumentBase();
          // Get the media filename info.
          // The applet tag should contain the path to the
          // source media file, relative to the html page.
          if ((mediaFile = getParameter("FILE")) == null)
               Fatal("Invalid media file parameter");
          try   {
               // Create an url from the file name and the url to the
               // document containing this applet.
               if ((url = new URL(codeBase, mediaFile)) == null)
               Fatal("Can't build URL for " + mediaFile);
               // Create an instance of a player for this media
               if ((player = Manager.createPlayer(url)) == null)
                    Fatal("Could not create player for "+url);
               // Add ourselves as a listener for player's events
               player.addControllerListener(this);
          }
          catch (MalformedURLException u)  {
               Fatal("Invalid media file URL!");
          }
          catch(IOException i)  {
               Fatal("IO exception creating player for "+url);
          }
          catch(NoPlayerException n)  {  //MB Changed
               Fatal("No Player Exception");
          }
          // This applet assumes that its start() calls
          // player.start().This causes the player to become
          // Realized. Once Realized, the Applet will get
          // the visual and control panel components and add
          // them to the Applet. These components are not added
          // during init() because they are long operations that
          // would make us appear unresposive to the user.
     }

     /**
     * Start media file playback. This function is called the
     * first time that the Applet runs and every
     * time the user re-enters the page.
     */
     public void start()  {
          // Call start() to prefetch and start the player.
          if (player != null) player.start();
     }

     /**
     * Stop media file playback and release resources before
     * leaving the page.
     */
     public void stop()   {
          if (player != null)  {
               player.stop();
               player.deallocate();
          }
     }

     /**
     * This controllerUpdate function must be defined in order
     * to implement a ControllerListener interface. This
     * function will be called whenever there is a media event.
     */
     public synchronized void controllerUpdate(ControllerEvent event)  {
          // If we're getting messages from a dead player,
          // just leave
          if (player == null) return;
          // When the player is Realized, get the visual
          // and control components and add them to the Applet
          if (event instanceof RealizeCompleteEvent)  {
               if ((visualComponent = player.getVisualComponent()) != null)
                    add("Center", visualComponent);
               if ((controlComponent = player.getControlPanelComponent()) != null)
                    add("South",controlComponent);
               // force the applet to draw the components
               validate();
          }
          else if (event instanceof CachingControlEvent)   {
               // Put a progress bar up when downloading starts,
               // take it down when downloading ends.
               CachingControlEvent e = (CachingControlEvent) event;
               CachingControl cc = e.getCachingControl();
               long cc_progress = e.getContentProgress();
               long cc_length = cc.getContentLength();
               // Add the bar if not already there ...
               if (progressBar == null)
                    if ((progressBar = cc.getProgressBarComponent()) != null)  {
                         add("North", progressBar);
                         validate();
                    }
               // Remove bar when finished ownloading
               if (progressBar != null)
                    if (cc_progress == cc_length)   {
                         remove (progressBar);
                         progressBar = null;
                         validate();
                    }
          }
          else if (event instanceof EndOfMediaEvent)  {
               // We've reached the end of the media; rewind and
               // start over
               player.setMediaTime(new Time(0));
               player.start();
          }
          else if (event instanceof ControllerErrorEvent)   {
               // Tell TypicalPlayerApplet.start() to call it a day
               player = null;
               Fatal (((ControllerErrorEvent)event).getMessage());
          }
     }

     void Fatal (String s)  {
          // Applications will make various choices about what
          // to do here. We print a message and then exit
          System.err.println("FATAL ERROR: " + s);
          throw new Error(s); // Invoke the uncaught exception
          // handler System.exit() is another
          // choice
     }
}
0
 
conickCommented:
You may want to check out which formats (and codecs) are supported by default.  With JMF2.0 you can plug in different codecs if yours isn't supported.
http://java.sun.com/products/java-media/jmf/2.0/supported.html

Remember to read the local file system you need a "signed" applet. (Otherwise it will give you a security exception).
0
 
jtjcompAuthor Commented:
Conick,
I have cut and paste your code into a
file named testplay.java when I try to compile it under visual j ++ I get the following error any ideas.
Public class 'typicalplayerapplet' should not be defined in testplay.java.
0
 
jtjcompAuthor Commented:
ovidciaciun,

That will play the file off of the net, I need it to use a file on the users local machine.
0
 
conickCommented:
Your problem is that the TypicalPlayerApplet class needs to be defined in a file called TypicalPlayerApplet.java (case sensitive).
Thats just the way Java works.

The code I gave wasnt a a copy/paste sort of thing.  It was just an example.  Some things you will have to do:
1) Modify how it finds the file.  Right now it looks on the server (relative to the HTML page) for the file.  To look at the local system you would need something like:
String mediaFile= "file://c:\\temp\\myAvi.avi";
player.setMediaLocator(new MediaLocator(mediaFile));
2) Make sure JMF is installed on the client side
3) Make sure you have permissions set up in the client browsers so that you CAN look at the local system.

Good luck getting JMF2.0 code to compile under Visual J++.  I don't believe you can plug in standard extensions with that IDE can you?
0
 
ovidiucraciunCommented:
I see you need an URL,
for the client machine that can be obtained like
URL local = new URL("file:///C:/avis/first.avi")
You'll have a problem with the nomber of "/" because Nescape needs three and
IE needs two and stand alone applicatin needs three.


0
 
jtjcompAuthor Commented:
Conick,
I'm getting very close to making this work.  When i run the applet i get an error, the error reads:
java.lang.error. invalid media file.
0
 
jtjcompAuthor Commented:
I'm sorry that is invalid media file parameter.
0
 
conickCommented:
Make sure the avi file is there... and local.
Can you give me the whole stacktrace?
Also the portion of the source that accesses the file.
0
 
jtjcompAuthor Commented:
Conick,
I got it working with your sample code, post a answer so i can give you  the points.
0
 
heyhey_Commented:
you must reject the current answer, than you can accept conick's comment as answer.
0
All Courses

From novice to tech pro — start learning today.