Monday, December 5, 2011

Playing Audiio file in j2me

package AudioSample;

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

public class PlayAudioMidlet extends MIDlet {
      private Display display;
      AudioPlayer ap;

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

      public void pauseApp() {
      }

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


package AudioSample;

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

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

      public AudioPlayer(PlayAudioMidlet 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 {
                        playAudio();
                  } 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) {
      }

      public void playAudio() {
            try {
                  player = Manager.createPlayer(getClass().getResourceAsStream("/res/filename.wav"), "audio/x-wav");
                  player.addPlayerListener(this);
                  player.setLoopCount(-1);
                  player.prefetch();
                  player.realize();
                  player.start();
            } catch (Exception e) {
            }
      }
}

No comments:

Post a Comment