Solved

Playing an AVI file using Java code

Posted on 2000-04-18
16
1,474 Views
Last Modified: 2008-02-01
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.
 
0
Comment
Question by:jtjcomp
  • 7
  • 4
  • 3
  • +1
16 Comments
 
LVL 16

Expert Comment

by:heyhey_
ID: 2728251
applet ? application ?
0
 
LVL 1

Author Comment

by:jtjcomp
ID: 2728274
applet
0
 
LVL 3

Expert Comment

by:ovidiucraciun
ID: 2728499
just sign for further responses ;)
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
LVL 1

Author Comment

by:jtjcomp
ID: 2728591
Is this a question that can not be answered, I'm I going about the task with the wrong langauge.
0
 
LVL 7

Expert Comment

by:conick
ID: 2728641
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
 
LVL 3

Accepted Solution

by:
ovidiucraciun earned 200 total points
ID: 2728785
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
 
LVL 7

Expert Comment

by:conick
ID: 2729069
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
 
LVL 1

Author Comment

by:jtjcomp
ID: 2730575
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
 
LVL 1

Author Comment

by:jtjcomp
ID: 2730583
ovidciaciun,

That will play the file off of the net, I need it to use a file on the users local machine.
0
 
LVL 7

Expert Comment

by:conick
ID: 2730664
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
 
LVL 3

Expert Comment

by:ovidiucraciun
ID: 2730674
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
 
LVL 1

Author Comment

by:jtjcomp
ID: 2731255
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
 
LVL 1

Author Comment

by:jtjcomp
ID: 2731260
I'm sorry that is invalid media file parameter.
0
 
LVL 7

Expert Comment

by:conick
ID: 2731276
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
 
LVL 1

Author Comment

by:jtjcomp
ID: 2732292
Conick,
I got it working with your sample code, post a answer so i can give you  the points.
0
 
LVL 16

Expert Comment

by:heyhey_
ID: 2733404
you must reject the current answer, than you can accept conick's comment as answer.
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ArrayIndexOutOfBoundException 9 80
replace a word with other 1 44
varialbe initialization 11 32
tomcat not starting 6 45
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This video teaches viewers about errors in exception handling.

786 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question