Home > Articles > Programming > Java

This chapter is from the book

Media Capture

For devices equipped with voice recorders or digital cameras, the MMAPI Player class can be used to capture audio clips or snap digital pictures. The media capturing support is currently available only on Series 60 devices and will come soon on future Series 40 devices. In this section, we use a Series 60–based multimedia blog application to demonstrate the media capture mechanisms. The mobile client allows users to take a picture, record a short audio clip, and then send both media files with a text note to a server. The server publishes the entries with timestamps to an HTML Web page in the chronological order. Any user can then view the blog entries from any xHTML-compatible browser on a PC or on a phone. The process is illustrated in Figure 9-7.

09fig07.jpg

Figure 9-7 The multimedia blog.

Capture Image

We can instantiate a video capture Player object by passing the URI locator capture://video to the Manager.createPlayer() factory method. Then, we can get a VideoControl control from the player and display the video UI window to the LCD using the techniques we discussed in the video playback section. Once the player is started, the user sees the live motion video of the camera view in the VideoControl UI. We can then call the VideoControl.getSnapshot() method to take a snapshot and store the photo to a byte array. The argument we pass to the getSnapshot() method determines the type and the dimensions of the resultant image. The following list is specific to Nokia 6600 and 3650 devices.

  • The getSnapshot(null) call captures a 160 by 120 PNG image.
  • The getSnapshot("encoding=jpeg") call captures a 160 by 120 JPEG image.
  • The getSnapshot("width=320&height=240") call captures a 320 by 240 PNG image.
  • The getSnapshot("encoding=jpeg&width=320&height=240") call captures a 320 by 240 JPEG image.

Three encoding values, png, jpeg, and bmp, are supported. The gif encoding is recently added to the Nokia 6600 maintenance release. If values are specified for width and height, both must be specified. If the requested dimensions are different from 160 by 120, the image is scaled to the requested width and height. If the aspect ratio requested does not match 4:3 (the default aspect ratio), the resulting image could be distorted. The maximum image size that can be captured depends on the free heap memory available.

09fig08.jpg

Figure 9-8 Camera viewfinder on the Series 60 emulator.

The following code shows how to develop a photo capture screen CameraView. When the user hits the action key or the capture menu, the camera takes a 320 by 240 JPEG snapshot image.

public class CameraView extends Form
            implements CommandListener {

  private Command capture;
  private Command skip;

  private Player player = null;
  private VideoControl video = null;

  public CameraView () {
    super ("Take a picture");

    showCamera ();

    capture = new Command ("Capture", Command.OK, 1);
    skip = new Command ("Skip", Command.CANCEL, 1);
    addCommand (capture);
    addCommand (skip);
    setCommandListener (this);
  }

  public void commandAction (Command c, Displayable d) {
    if (c == capture) {
      capture ();
      BlogClient.showPhotoPreview ();
  } else if (c == skip) {
    player.close ();
    BlogClient.showAudioRecorder ();

  }
}

private void showCamera () {
  try {
    player = Manager.createPlayer("capture://video");
    player.realize();

    // Add the video playback window (item)
    video = (VideoControl) player.getControl(
                                        "VideoControl");
    Item item = (Item) video.initDisplayMode(
        GUIControl.USE_GUI_PRIMITIVE, null);
    item.setLayout(Item.LAYOUT_CENTER |
                    Item.LAYOUT_NEWLINE_AFTER);
    append (item);
    // Add a caption
    StringItem s = new StringItem ("", "View finder");
    s.setLayout(Item.LAYOUT_CENTER);
    append (s);

    player.start();

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

private void capture () {
  try {
    // PNG, 160x120
    // BlogClient.photoData = video.getSnapshot(null);
    //      OR
    // BlogClient.photoData = video.getSnapshot(
    //     "encoding=png&width=160&height=120");

    // BlogClient.photoPreview = BlogClient.photoData;
    // BlogClient.photoType = "png";

    byte [] tmp = video.getSnapshot(
        "encoding=jpeg&width=320&height=240");
    BlogClient.photoPreview =
           BlogClient.createPreview(
              Image.createImage(tmp, 0, tmp.length));
      BlogClient.photoData = tmp;
      BlogClient.photoType = "jpg";

      player.stop ();
      player.close ();

    } catch (Exception e) {
      e.printStackTrace ();
      BlogClient.showAlert ("Error", e.getMessage ());
    }
  }
}

The BlogClient.createPreview() method resizes the snapshot to a smaller preview image, which fits into the device screen. The method first creates an empty image of the preview size. It then populates the preview image pixel by pixel by sampling the original image. This method creates an approximate thumbnail without parsing the original JPEG image.

// Scale down the image by skipping pixels
public static Image createPreview (Image image) {
  int sw = image.getWidth();
  int sh = image.getHeight();

  int pw = 160;
  int ph = pw * sh / sw;

  Image temp = Image.createImage(pw, ph);
  Graphics g = temp.getGraphics();

  for (int y = 0; y < ph; y++) {
    for (int x = 0; x < pw; x++) {
      g.setClip(x, y, 1, 1);
      int dx = x * sw / pw;
      int dy = y * sh / ph;
      g.drawImage(image, x - dx, y - dy,
          Graphics.LEFT | Graphics.TOP);
    }
  }

  Image preview = Image.createImage(temp);
  return preview;
}

The PhotoReview class shows the review image and asks the user whether to continue.

public class PhotoPreview extends Form
              implements CommandListener {

  private Command cancel;
  private Command next;

  public PhotoPreview () {
    super ("Photo Preview");
    cancel = new Command ("Cancel", Command.CANCEL, 1);
    next = new Command ("Next", Command.OK, 1);
    addCommand (cancel);
    addCommand (next);
    setCommandListener (this);

    append (new ImageItem (
        "Image size is " + BlogClient.photoData.length,
        BlogClient.photoPreview,
        ImageItem.LAYOUT_CENTER, "image"));
  }

  public void commandAction (Command c, Displayable d) {
    if (c == cancel) {
      BlogClient.initSession();
      BlogClient.showCamera ();

    } else if (c == next) {
      BlogClient.showAudioRecorder();
    }
  }
}

Capture Audio

After the user is satisfied with the photo, she can record an audio message. The audio capture player is instantiated using the capture://audio URI locator. Arguments to this string are used to specify audio bitrate and sampling depth. For example, the capture://audio?rate=8000&bits=16 URI locator string initiates a Player object and captures 16-bit sound at 8,000 bits per second. Once we have the Player instance, we can get a RecordControl control and use its setRecordStream() method to assign an OutputStream to this control. The default audio output format is the wav format in Nokia 6600 and 3650 devices. The RecordControl starts recording once the player enters the started state and stops once the player is stopped.

The source code for the AudioRecorder class is listed below. When the user stops the audio capturing player, the program writes out the recorded audio data to a byte array, audioData.

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 ();
    }
  }
}

Submit Blog Entries

After we have gathered the snapshot, audio recording, and short text message data, we can submit it to the server. The code below illustrates how it works. The complete source code with multithread support is available in the BlogClient class.

HttpConnection conn = null;
DataInputStream din = null;
DataOutputStream dout = null;

conn = (HttpConnection) Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);

dout = conn.openDataOutputStream ();
dout.writeInt (PHOTO_AUDIO);
dout.writeUTF (message);
dout.writeUTF (photoType);
dout.writeInt (photoData.length);
dout.write (photoData, 0, photoData.length);
dout.writeInt (audioData.length);
dout.write (audioData, 0, audioData.length);

dout.flush ();
dout.close ();

The Blog Servlet

On the server side, the blog servlet intercepts the HTTP POST data in the doPost() method. It stores image and audio data into separate files and appends links to an HTML master file. The doGet() method is invoked when a client accesses the servlet directly from a browser. It assembles and returns an HTML page with up-to-date blog entries. The full source code of the servlet is listed below for your reference.

public class BlogServlet extends HttpServlet {
  private static int NO_OBJECT = 0;
  private static int PHOTO_ONLY = 1;
  private static int AUDIO_ONLY = 2;
  private static int PHOTO_AUDIO = 3;

  private static int SUCCESS = 1;
  private static int FAILURE = 2;

  private static String fileroot = null;
  private static String webroot = null;

  public void init() throws ServletException {
    InputStream in =
        getClass().getResourceAsStream("/conf.prop");
    Properties prop = new Properties ();
    try {
      prop.load (in);
      fileroot = prop.getProperty("Fileroot");
      webroot = prop.getProperty("Webroot");
    } catch (Exception e) {
      e.printStackTrace ();
      fileroot = "/root/BlogServer/content/";
      webroot = "/BlogServer/content/";
    }
  }

public void doGet(HttpServletRequest request,
                   HttpServletResponse response)
            throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();

  out.println(readTextFile("header.html"));
  out.println(readTextFile("entries.html"));
  out.println(readTextFile("footer.html"));

  out.flush ();
  out.close ();
}

public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
             throws ServletException, IOException {

  response.setContentType("application/binary");

  InputStream in = request.getInputStream();
  OutputStream out = response.getOutputStream();
  DataInputStream din = new DataInputStream(in);
  DataOutputStream dout = new DataOutputStream(out);

  String current =
      Long.toString((new Date()).getTime());
  String body = "<b>Posted at</b>: " +
      (new Date()).toString() + "<br/>";
  String filename;

  // Get the opcode
  int opcode = din.readInt();
  // Get the message body
  body += din.readUTF();
  body += "<br/>";

  if (opcode == NO_OBJECT) {
    // Save the message body
    saveMessage (body);
    dout.writeInt(SUCCESS);

  } else if (opcode == PHOTO_ONLY) {
    // Get photo data
    String photoType = din.readUTF ();
    byte [] photoData = receiveObject (din);

    // Save the photo data
    filename = current + "." + photoType;
    saveObject (photoData, filename);
    body = body + photoHtml(filename);

    // Save the message body
    saveMessage (body);
    dout.writeInt(SUCCESS);

  } else if (opcode == AUDIO_ONLY) {
    // Get the audio data
    byte [] audioData = receiveObject (din);

    // Save the audio data in a file
    filename = current + ".wav";
    saveObject (audioData, filename);
    body = body + audioHtml(filename);

    // Save the message body
    saveMessage (body);
    dout.writeInt(SUCCESS);

  } else if (opcode == PHOTO_AUDIO) {
    // Get the photo data
    String photoType = din.readUTF ();
    byte [] photoData = receiveObject (din);
    // Get the audio data
    byte [] audioData = receiveObject (din);

    // Save the photo data in a file
    filename = current + "." + photoType;
    saveObject (photoData, filename);
    body = body + photoHtml(filename);

    // Save the audio data in a file
    filename = current + ".wav";
    saveObject (audioData, filename);
    body = body + audioHtml(filename);

    // Save the message body
    saveMessage (body);
    dout.writeInt(SUCCESS);

  } else {
    dout.writeInt(FAILURE);
  }
  dout.flush();
  dout.close();
  din.close();
  in.close();
  out.close();
}

private byte [] receiveObject (DataInputStream din)
                                   throws IOException {
  int length = din.readInt();
  byte [] buf = new byte [length];
  din.readFully (buf);
  return buf;
}

private void saveObject (byte [] data, String name)
                                    throws IOException {
  FileOutputStream fout =
      new FileOutputStream(fileroot + name);
  fout.write(data, 0, data.length);
  fout.flush ();
  fout.close ();
}

private void saveMessage (String body)
                        throws IOException {
  body = body + "<hr/>";
  FileWriter writer =
    new FileWriter (fileroot + "entries.html", true);
  writer.write(body, 0, body.length());
  writer.flush ();
  writer.close ();
}

private String photoHtml (String filename) {
  return "<img src=\"" + webroot + filename +
          "\"/>" + "<br/>";
}

private String audioHtml (String filename) {
  return "<a href=\"" + webroot + filename +
    "\">" + "Audio file (wav format)</a>" + "<br/>";
}

private String readTextFile (String name)
                         throws IOException {
  StringBuffer result = new StringBuffer ();
  FileReader reader =
       new FileReader (fileroot + name);

    char [] buf = new char [256];
    int i = 0;
    while ( (i = reader.read(buf)) != -1 ) {
      result.append(buf, 0, i);
    }
    reader.close();
    return result.toString ();
  }
}

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020