Monday, December 5, 2011

Playing Video file in j2me

package VideoSample;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class PlayVideoMidlet extends MIDlet {
      private Display display;
      VideoPlayer vp;

      public void startApp() {
            display = Display.getDisplay(this);
            vp = new VideoPlayer(this, display);
            display.setCurrent(vp);
      }

      public void pauseApp() {
      }

      public void destroyApp(boolean unconditional) {
            notifyDestroyed();
      }
}

package VideoSample;

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.VideoControl;

public class VideoPlayer extends Form implements CommandListener, PlayerListener {
PlayVideoMidlet midlet;
private Display display;
private Command play, stop, exit;
private Player player;

      public VideoPlayer(PlayVideoMidlet midlet, Display display) {
            super("");
            this.midlet = midlet;
            this.display = Display.getDisplay(midlet);
            play = new Command("Play", Command.OK, 0);
            stop = new Command("Stop", Command.STOP, 0);
            exit = new Command("Exit", Command.EXIT, 0);
            addCommand(play);
            addCommand(stop);
            addCommand(exit);
            setCommandListener(this);
      }

      public void commandAction(Command c, Displayable d) {
            if (c == play) {
                  try {
                           playVideo();
                  } catch (Exception e) {
                  }
            } else if (c == stop) {
                  player.close();
            } else if (c == exit) {
                  if (player != null) {
                           player.close();
                  }
                  midlet.destroyApp(false);
            }
      }

      public void playerUpdate(Player player, String event, Object eventData) {
            if (event.equals(PlayerListener.STARTED) && new Long(0L).equals((Long) eventData)) {
                  VideoControl vc = null;
                  if ((vc = (VideoControl) player.getControl("VideoControl")) != null) {
                           Item videoDisp = (Item) vc.initDisplayMode(vc.USE_GUI_PRIMITIVE, null);
                           append(videoDisp);
                  }
                  display.setCurrent(this);
            } else if (event.equals(PlayerListener.CLOSED)) {
                  deleteAll();
            }
      }

      public void playVideo() {
            try {
                  player = Manager.createPlayer(getClass().getResourceAsStream("/res/filename.mpg"), "video/mpeg");
                  player.addPlayerListener(this);
                  player.setLoopCount(-1);
                  player.prefetch();
                  player.realize();
                  player.start();
            } catch (Exception e) {
            }
      }
}

No comments:

Post a Comment