Home > Articles > Programming > Java

This chapter is from the book

Simple Audio Playback

The MMAPI implementation on standard Series 40 Developer Platform (e.g., the Nokia 6230 device) supports MIDI and tones playback. In this section, we walk through the source code of a MIDI player MIDlet. We cover MIDI player Controls that are supported on the Series 40 Developer Platform. This example MIDlet is tested on a Nokia 6230 device. When the MidiPlayer MIDlet is started, it shows a screen of playback options (Figure 9-3). Each UI component corresponds to an option in a player Control. When the MIDI file playback is started, the MIDlet displays a status page showing the playback volume of each MIDI channel (Figure 9-4).

09fig03.jpg

Figure 9-3 Playback options in the MidiPlayer MIDlet UI.

09fig04.jpg

Figure 9-4 The MIDI channel volumes.

The MidiPlayer MIDlet

The MidiPlayer class extends the MIDlet class and implements the CommandAction interface. It manages two Form objects: the playerOptions is for the option screen, and the playerStates is for the MIDI channel volume screen. The MidiPlayer class source code is shown below. The constructor retrieves the paths to the local and remote MIDI files from the JAD attributes. The startApp() method builds and displays the UI for the playback options screen.

public class MidiPlayer extends MIDlet
            implements CommandListener {

private Display display;
private Command exit;
private Command play;
private Command back;

private TempoControl tempoControl;
private MIDIControl midiControl;
private RateControl rateControl;
private PitchControl pitchControl;
private VolumeControl volumeControl;
private StopTimeControl stopControl;

private TextField tempoField;
private TextField pitchField;
private TextField rateField;
private Gauge volumeGauge;
private Gauge stopGauge;
private ChoiceGroup config;

private Form playerOptions = null;
private Form playerStates = null;

// media file location
public static String mediaMidi;
public static String remotePrefix;
public static String localPrefix;

public MidiPlayer () {
  display = Display.getDisplay(this);
  mediaMidi = getAppProperty ("MediaMidi");
  remotePrefix = getAppProperty ("RemotePrefix");
  localPrefix = getAppProperty ("LocalPrefix");

  exit = new Command ("Done", Command.EXIT, 1);
  play = new Command ("Play", Command.OK, 1);
  back = new Command ("Back", Command.BACK, 1);
}

protected void startApp () {
  playerOptions = new Form ("Midi player");
  playerOptions.addCommand (exit);
  playerOptions.addCommand (play);
  playerOptions.setCommandListener (this);

  tempoField = new TextField (
      "Tempo", "100000", 7, TextField.NUMERIC);
  pitchField = new TextField (
      "Pitch", "0", 7, TextField.NUMERIC);
  rateField = new TextField (
       "Rate", "100000", 7, TextField.NUMERIC);

  volumeGauge = new Gauge ("Vol", true, 10, 5);
  stopGauge = new Gauge ("Stop time", true, 20, 20);

  config = new ChoiceGroup ("", Choice.MULTIPLE);
  config.append ("Play local file?", null);
  config.append ("Play backwards?", null);

  playerOptions.append (tempoField);
  playerOptions.append (pitchField);
  playerOptions.append (rateField);
  playerOptions.append (stopGauge);
  playerOptions.append (volumeGauge);
  playerOptions.append (config);

  display.setCurrent (playerOptions);
}

protected void pauseApp () {
  // Do nothing
}

protected void destroyApp (boolean unconditional) {
  // Do nothing
}

public void commandAction (Command c, Displayable d) {
  if (c == exit) {
    destroyApp (true);
    notifyDestroyed ();

  } else if (c == play) {
    try {
      playMidi ();
      showStates ();
    } catch (Exception e) {
      e.printStackTrace ();
    }

  } else if (c == back) {
    display.setCurrent (playerOptions);
  }
  }

  // playMidi() and showStates() methods ... ...
}

The playMidi() and showStates() methods, which are left out of the above code listing, did the real work related to the MMAPI. Now, let's look at those methods more carefully.

Create the Player

The playMidi() method first creates a media player for the MIDI file. Recall that the first checkbox (index zero) in the config component on the playback options screen is "Play local file?" If it is checked, we create a player from a MIDI file bundled in the MIDlet JAR file and manually pass the audio/midi MIME type string to the createPlayer() method. If it is not checked, we create a player from the remote URL. In that case, the MIME type is returned from the server. After the player is created, we realize it, instantiate the controls, set control values, and start the player.

public void playMidi () throws Exception {
    Player player;

    // Check if the first check box in config is selected
    if (config.isSelected(0)) {
      InputStream is =
          this.getClass().getResourceAsStream (
              localPrefix + mediaMidi);
      player = Manager.createPlayer(is, "audio/midi");
    } else {
      player = Manager.createPlayer(
          remotePrefix + mediaMidi);
    }
    player.addPlayerListener(new StopListener ());
    player.realize();

    // Fix the controls ... ...

    player.start ();
 }

Player Events

In the playMidi() method, the player.start() statement returns after the playback begins, and the MIDI file plays in the background. In our application, we would like to be notified when the playback process is actually finished so that we can free up the player resources. It is critically important that we close players as soon as we are finished using them. It frees up system resources for other applications and reduces power consumption. Also, we want to pause the playback when the MIDI device is being interrupted by a high-priority system event such as an incoming phone call. The PlayerListener interface provides mechanisms for such notifications and callbacks.

In the playMidi() method code, we added a PlayerListener object to listen for any events in the audio player. The StopListener object's playerUpdate() method is called whenever a player event or an exception occurs. The StopListener object captures the events that correspond to the player-stopping event and puts the player back to closed state.

public class StopListener implements PlayerListener {

  public void playerUpdate (Player player,
                  String event, Object eventData) {
    try {
      if (event.equals (STOPPED) ||
          event.equals (STOPPED_AT_TIME) ||
          event.equals (ERROR) ||
          event.equals (END_OF_MEDIA)) {
        // Playback is finished
        player.deallocate ();
        player.close ();
        player = null;

      } else if (event.equals(DEVICE_UNAVAILABLE)) {
        // Incoming phone call
        player.stop();

      } else if (event.equals(DEVICE_AVAILABLE)) {
        // Finished phone call.
        // Start from where we left off
        player.start();
      }
      System.out.println(event);

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

Player Controls

In the playMidi() method, we set up the player controls before starting it. The standard controls supported in Series 40 Developer Platform are VolumeControl, StopTimeControl, TempoControl, PitchControl, RateControl, and MIDIControl. The code is listed as follows.

public void playMidi () throws Exception {

  // ... ...
  player.realize();

  volumeControl = (VolumeControl) player.getControl(
      "VolumeControl");
  // The volume is from 0 to 100
  volumeControl.setLevel (
      volumeGauge.getValue() * 10);

  stopControl = (StopTimeControl) player.getControl(
      "StopTimeControl");
  // The argument microsecond NOT millisecond!
  stopControl.setStopTime (
      stopGauge.getValue() * 1000000);

  tempoControl = (TempoControl) player.getControl (
      "TempoControl");
  int t = Integer.parseInt (tempoField.getString());
  tempoControl.setTempo(t);

  pitchControl = (PitchControl) player.getControl (
      "PitchControl");
  int p = Integer.parseInt (pitchField.getString());
  pitchControl.setPitch(p);

  rateControl = (RateControl) player.getControl (
      "RateControl");
  int r = Integer.parseInt (rateField.getString());
  // Check whether to reverse playback direction
  if (config.isSelected(1)) {
    r = -1 * r;
  }
  rateControl.setRate(r);
  midiControl = (MIDIControl) player.getControl (
      "MIDIControl");

  player.start ();
}

Now, let's check out those controls one by one.

VolumeControl

The VolumeControl object controls the sound volume of the player. We can mute the player via the setMute() method and set the volume using a linear scale from 1 to 100 via setLevel() method. In the MidiPlayer example, each step in the stopGauge gauge corresponds to a volume level change of 10. If the volume changes during the playback, a VOLUME_CHANGED event is delivered to the registered PlayerListener.

StopTimeControl

The StopTimeControl object allows us to preset a stop time for the player. The argument for the setStopTime() time is a long value for microseconds. In the MidiPlayer example, each step in the stopGauge gauge is one second in media play time.

TempoControl

The TempoControl object controls the tempo, which is often specified by beats per second, of a song. To allow fractional beats per minute, the setTempo() method takes in the milli-beat value, which is the beat per minute value multiplied by 1,000.

RateControl

Specifying the absolute tempo of a song is not always a good idea, since the absolute tempo is often overridden by the MIDI file. The RateControl object is used to set a relative tempo multiplier for all absolute tempo settings in this player. The rate, defined as a milli-percentage, is the ratio of the player's media time and the actual TimeBase. For example, a rate of 200,000 (2 x 100 percent x 1,000 milli) indicates that for every 1 second of TimeBase time (the real time), the player needs to play 2 seconds worth of media content. That makes the playback go faster. If the rate is a negative value, the playback would be backwards. The default playback rate is 100,000, which means that there is no change to the absolute tempo. Custom rate factors can be set via the setRate() method. The getMaxRate() and getMinRate() methods return the maximum and minimum rates supported by this device.

PitchControl

The PitchControl object raises or lowers the playback pitch without changing the playback speed. The argument for the setPitch() method is for milli-semitones. For example, a pitch value of 12,000 raises the pitch by 12 semitones and increases the frequency of perceived sound by a factor of 2.

MIDIControl

The MIDIControl object provides advanced access to the MIDI device. It gets or sets the volumes and assigned programs of each of the 16 MIDI channels. The showStates() method shows the volumes of the MIDI channels in the current player.

public void showStates () {
  playerStates = new Form ("Channel Vols");
  playerStates.addCommand (back);
  playerStates.setCommandListener (this);

  for (int i = 0; i <= 15; i++) {
    playerStates.append ("\n " + i + ": " +
        Integer.toString(
            midiControl.getChannelVolume(i)));
  }

  display.setCurrent(playerStates);
}

The MIDIControl object can also be used to send MIDI events to the device. MIDI events support is currently only available on the Nokia 3300, 6230, and 7600 devices. It is planned for future Series 40 devices.

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