Java Tutorial/J2ME/StopTimeControl

Материал из Java эксперт
Перейти к: навигация, поиск

Stop Time Control

import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.StopTimeControl;
import javax.microedition.midlet.MIDlet;
public class StopTimeControlMIDlet extends MIDlet implements CommandListener, PlayerListener {
  private Display display = Display.getDisplay(this);
  private Alert alert = new Alert("Message");
  private List list = new List("Pick One", List.IMPLICIT);
  private Command exitCommand = new Command("Exit", Command.EXIT, 1);
  private Command okCommand = new Command("Ok", Command.OK, 1);
  private Player player = null;
  private StopTimeControl stControl = (StopTimeControl) player
  .getControl("javax.microedition.media.control.StopTimeControl");
  public StopTimeControlMIDlet() {
    alert.addCommand(exitCommand);
    list.append("Play full", null);
    list.append("Use StopTimeControl", null);
    list.addCommand(exitCommand);
    alert.addCommand(okCommand);
    alert.setCommandListener(this);
    list.setCommandListener(this);
    try {
      player = Manager.createPlayer(getClass().getResourceAsStream("/r.wav"), "audio/x-wav");
      player.addPlayerListener(this);
      player.prefetch();
    } catch (Exception e) {
    }
  }
  public void startApp() {
    display.setCurrent(list);
  }
  public void pauseApp() {
  }
  public void destroyApp(boolean unconditional) {
  }
  public void commandAction(Command cmd, Displayable disp) {
    if (cmd == exitCommand) {
      notifyDestroyed();
      return;
    }
    if (cmd == okCommand) {
      try {
        player.stop();
        display.setCurrent(list);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    if (disp == list) {
      int selectedIdx = list.getSelectedIndex();
      display.setCurrent(alert);
      try {
        if (selectedIdx == 0) {
          if (player != null)
            player.start();
          alert.setString("Started without StopTimeControl ...");
        } else {
          stControl.setStopTime(player.getDuration() / 2);
          if (player != null)
            player.start();
          alert.setString("Started WITH StopTimeControl ...");
       }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
  public void playerUpdate(Player player, String event, Object eventData) {
    if (event == STOPPED_AT_TIME) {
      alert.setString("Stopped at: " + eventData + " microseconds" + ", actual duration: "
          + player.getDuration() + " microseconds");
      alert.setTimeout(Alert.FOREVER);
      display.setCurrent(alert);
    }
  }
}