package com.Series40Book;

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;


public class AudioRecorder extends Form
              implements CommandListener {

  private Command skip;
  private Command start;
  private Command stop;

  private Player player = null;
  private RecordControl recordcontrol = null;
  private ByteArrayOutputStream output = null;


  public AudioRecorder () {
    super ("Audio Recorder");

    skip = new Command ("Skip", Command.CANCEL, 1);
    start = new Command ("Start", Command.OK, 1);
    stop = new Command ("Stop", Command.SCREEN, 1);
    addCommand (skip);
    addCommand (start);
    addCommand (stop);
    setCommandListener (this);

    append ("Use the Start menu to start recording. " +
        "Use the Stop menu to stop recording");
    try {
      player = Manager.createPlayer(
          "capture://audio?rate=8000&bits=16");
      player.realize ();
      recordcontrol =
  (RecordControl) player.getControl("RecordControl");
      output = new ByteArrayOutputStream ();
      recordcontrol.setRecordStream(output);

    } catch (Exception e) {
      e.printStackTrace ();
    }
  }

  public void commandAction (Command c, Displayable d) {
    if (c == skip) {
      BlogClient.showMessageForm ();

    } else if (c == start) {
      try {
        recordcontrol.startRecord();
        player.start();
      } catch (Exception e) {
        e.printStackTrace ();
        BlogClient.showAlert ("Error",
            "Cannot start the player. " +
            "Maybe audio recoding is not supported " +
            "on this device. Please skip this step");
      }

    } else if (c == stop) {
      try {
        recordcontrol.commit ();
        player.close();
      } catch (Exception e) {
        e.printStackTrace ();
        BlogClient.showAlert ("Error",
            "Cannot stop the player");
      }
      BlogClient.audioData = output.toByteArray();
      BlogClient.showMessageForm ();
    }
  }
}
