Java/J2ME/Audio Media

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

Audio MIDlet

   <source lang="java">

/* Wireless Java 2nd edition Jonathan Knudsen Publisher: Apress ISBN: 1590590775

  • /

import java.io.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.media.*; public class AudioMIDlet

   extends MIDlet
   implements CommandListener, Runnable {
 private Display mDisplay;
 private List mMainScreen;
 
 public void startApp() {
   mDisplay = Display.getDisplay(this);
   
   if (mMainScreen == null) {
     mMainScreen = new List("AudioMIDlet", List.IMPLICIT);
 
     mMainScreen.append("Via HTTP", null);
     mMainScreen.append("From resource", null);
     mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
     mMainScreen.addCommand(new Command("Play", Command.SCREEN, 0));
     mMainScreen.setCommandListener(this);
   }
   mDisplay.setCurrent(mMainScreen);
 }
 public void pauseApp() {}
 public void destroyApp(boolean unconditional) {}
 
 public void commandAction(Command c, Displayable s) {
   if (c.getCommandType() == Command.EXIT) notifyDestroyed();
   else {
     Form waitForm = new Form("Loading...");
     mDisplay.setCurrent(waitForm);
     Thread t = new Thread(this);
     t.start();
   }
 }
 public void run() {
   String selection = mMainScreen.getString(
       mMainScreen.getSelectedIndex());
   boolean viaHttp = selection.equals("Via HTTP");
   if (viaHttp)
     playViaHttp();
   else
     playFromResource();
 }
 
 private void playViaHttp() {
   try {
     String url = getAppProperty("AudioMIDlet-URL");
     Player player = Manager.createPlayer(url);
     player.start();
   }
   catch (Exception e) {
     showException(e);
     return;
   }
   mDisplay.setCurrent(mMainScreen);
 }
 
 private void playFromResource() {
   try {
     InputStream in = getClass().getResourceAsStream("/relax.wav");
     Player player = Manager.createPlayer(in, "audio/x-wav");
     player.start();
   }
   catch (Exception e) {
     showException(e);
     return;
   }
   mDisplay.setCurrent(mMainScreen);
 }
 
 private void showException(Exception e) {
   Alert a = new Alert("Exception", e.toString(), null, null);
   a.setTimeout(Alert.FOREVER);
   mDisplay.setCurrent(a, mMainScreen);
 }

}


      </source>
   
  
 
  



demonstrate the functionality supported by javax.microedition.lcdui package.

   <source lang="java">

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /* MIDlet to demonstrate the functionality supported by javax.microedition.lcdui package. Make changes inside the constructor (SimpleMIDlet() method) and inside the startApp() method to see all the different functionality in this package.

      • High-level APIs
   ---------------

1. testForm() method demonstrates a variety of formElements which are individually

  instantiated from inside the addItemsToForm() method

2. testAlert() method throws up an Alert on top of an existing form when the SCREEN

  button on the form is clicked

3. testList() and testBox() methods demonstrate the use of IMPLICIT List and TextBox

  respectively
      • Low-level APIs
   --------------

testCanvas()method demonstrates the use of low-level APIs

  • /

public class SimpleMIDlet extends MIDlet implements CommandListener, ItemStateListener {

   Form simpleForm;
   List simpleList;
   TextBox simpleTextBox;
   Alert simpleAlert;
   SimpleCanvas simpleCanvas;
   Ticker t;
   Command c1 = new Command("Back", Command.BACK, 1);
   Command c2 = new Command("Screen", Command.SCREEN, 1);
   Command c3 = new Command("OK", Command.OK, 1);
   public SimpleMIDlet (){
 // High-level API examples
 
 // 1. Form and form elements: 
 //        a. Uncomment corresponding line in startApp() also
 //        b. Uncomment following line and comment out all other lines   
 testForm();
 
 // 2. Alert example; click on the SCREEN button to see the Alert
 //        a. Uncomment corresponding line in startApp() also
 //        b. Uncomment following line and comment out all other lines
 // testAlert();
 // 3. IMPLICIT List example
 //        a. Uncomment corresponding line in startApp() also
 //        b. Uncomment following line and comment out all other lines   
 // testList();
 // 4. TextBox example
 //        a. Uncomment corresponding line in startApp() also
 //        b. Uncomment following line and comment out all other lines   
 // testTextBox();
 
 // Low-level API examples
 //        a. Uncomment corresponding line in startApp() also
 //        b. Uncomment following line and comment out all other lines
 // testCanvas();
   }
   protected void destroyApp(boolean unconditional) {
   }
   protected  void pauseApp() {
   }
   private void testForm() {
 simpleForm  = new Form("Simple Form");
 // Create and add a new ticker to the Form
 t = new Ticker("Tick tock tick tock");
 simpleForm.setTicker(t);
 // Add a few Commands to the Form
 simpleForm.addCommand(c1);
 simpleForm.addCommand(c2);
 simpleForm.addCommand(c3);
 addItemsToForm();
   }
   private void addItemsToForm() {
 addChoiceGroup();
 addDateField();
 addGauge();
 addImageItem();
 addTextField();
   }
   private void addChoiceGroup() {
 Image icon = null;
 // Load image
 try {
     icon = Image.createImage("/midp/simpleMIDlet/Icon.png");
 }
 catch (java.io.IOException e) {
     System.out.println("Could not load image. Exception: " + e);
 }
 // Image choices
 Image[] imageArray = new Image[]{ icon, icon, icon };
 String[] stringArray = { "Choice 1", 
        "Choice 2", 
        "Choice 3" };
 // Set up an exclusive choice group
 ChoiceGroup cGroup1 = new ChoiceGroup("Exclusive",
               ChoiceGroup.EXCLUSIVE,
               stringArray,
               imageArray);
 // Set up a multiple choice choice group
 ChoiceGroup cGroup2 = new ChoiceGroup("Multiple",
               ChoiceGroup.MULTIPLE,
               stringArray,
               imageArray);
 simpleForm.append( cGroup1 );
 simpleForm.append( cGroup2 );
 simpleForm.setItemStateListener(this);
   }
   
   public void itemStateChanged (Item item) {
 if( item.getLabel().equals("Exclusive")) { 
     int choice = ((ChoiceGroup)item).getSelectedIndex();
     switch (choice) {
     case 0: 
   simpleForm.append("\nSelection: 0\n");
   break;
     case 1:
   simpleForm.append("\nSelection: 1\n");
   break;
     case 2:
   simpleForm.append("\nSelection: 2\n");
   break;
     }
 }
   }
   private void addDateField() {
 simpleForm.append(new DateField("Date", DateField.DATE));
       simpleForm.append(new DateField("Date & Time", DateField.DATE_TIME));
   }
   private void addGauge() {
 // Add an interactive gauge with the maximum value of 100 
 // and an initial value of 50 
 simpleForm.append(new Gauge("Interactive", true, 100, 50));
 
 // Add a  non-interactive gauge
 simpleForm.append(new Gauge("Non-interactive", false, 100, 50));
   }
   private void addImageItem() {
 Image image = null;
       try {
     image = Image.createImage("/midp/SimpleMIDlet/JavaPowered-8.png");
 }
       catch(java.io.IOException e) {
     System.out.println("Could not load image. Exception: " + e);
       }
 simpleForm.append(
       new ImageItem("Default layout",
         image,
         ImageItem.LAYOUT_LEFT + ImageItem.LAYOUT_NEWLINE_BEFORE,
         "Image not visible"));
 
   }
   
   private void addTextField() {
 simpleForm.append(new TextField("Any character", "", 15, TextField.ANY));
       simpleForm.append(new TextField("Email address", "", 20, TextField.EMAILADDR));
       simpleForm.append(new TextField("Numeric", "", 10, TextField.NUMERIC));
       simpleForm.append(new TextField("Phone", "", 12, TextField.PHONENUMBER));
       simpleForm.append(new TextField("Password", "", 6, TextField.PASSWORD));
       simpleForm.append(new TextField("URL", "", 30, TextField.URL));
 
   }
   private void testList() {
 String[] listElems = {
     "Element 1",
     "Element 2",
     "Element 3",
     "Element 4",
     "Element 5",
     "Element 6",
     "Element 7",
     "Element 8",
     "Element 9"
 };
 
 simpleList = new List("List", List.IMPLICIT, listElems, null);
   }
   private void testTextBox() {
 simpleTextBox = new TextBox("Textbox", "4154", 10, TextField.PASSWORD);
   }
   private void testAlert() {
 testForm();
 simpleAlert = new Alert("Alert");
       simpleAlert.setTimeout(Alert.FOREVER);
       simpleAlert.setString("This is a test Alert");
       simpleAlert.setType(AlertType.INFO);
   }
   private void testCanvas() {
 simpleCanvas = new SimpleCanvas();
   }
   public void commandAction(Command c, Displayable d) {
 if ( c.getCommandType() == Command.BACK ) {
     // Go back
 }
 if ( c.getCommandType() == Command.SCREEN ) {
     Display.getDisplay(this).setCurrent(simpleAlert, simpleForm);
 }
   }
   protected void startApp() {
 SimpleMIDlet simpleMIDlet = new SimpleMIDlet();
 
 // High-level API examples
 // 1. Uncomment the following two lines for Form and Alert examples and comment all others
       Display.getDisplay(this).setCurrent(simpleMIDlet.simpleForm);
 simpleMIDlet.simpleForm.setCommandListener(this);
 // 2. Uncomment following line for IMPLICIT List example and comment all others
 // Display.getDisplay(this).setCurrent(simpleMIDlet.simpleList);
 // 3. Uncomment following line for TextBox examples and comment all others
 // Display.getDisplay(this).setCurrent(simpleMIDlet.simpleTextBox);
 // Low-level API examples 
 // Uncomment following line and comment all others
 // Display.getDisplay(this).setCurrent(simpleMIDlet.simpleCanvas);
   }

} class SimpleCanvas extends Canvas {

   int width, height;
   int widthShift, heightShift;
   String displayString;
   public SimpleCanvas( ){
 super();
 width = getWidth() - 1;
 height = getHeight() - 1;
 widthShift = 0;
 heightShift = 0;
 displayString = "Hello World";
   } 

   protected void paint( Graphics g ){
       g.setColor( 0xffffff );
       g.fillRect( 0, 0, width, height );
       g.setColor( 0 );
       g.drawString( displayString, width/2 + widthShift, height/2 + heightShift,
                      g.TOP | g.HCENTER );
   }
   public void keyPressed( int keyCode) {
 int action = getGameAction(keyCode);
 switch (action) {
 case LEFT:
     widthShift -= 2;
     break;
 case RIGHT:
     widthShift += 2;
     break;
 case UP:
     heightShift -= 2;
     break;
 case DOWN:
     heightShift += 2;
     break;
 case FIRE:
     displayString = "Boom!";
     break;
 }
 repaint();
   }

}


      </source>
   
  
 
  



Media Information MIDlet

   <source lang="java">

/* Wireless Java 2nd edition Jonathan Knudsen Publisher: Apress ISBN: 1590590775

  • /

import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.media.*; public class MediaInformationMIDlet extends MIDlet implements CommandListener {

 private Form mInformationForm;
 
 public void startApp() {
   if (mInformationForm == null) {
     mInformationForm =
         new Form("Content types and protocols");
     String[] contentTypes =
         Manager.getSupportedContentTypes(null);
     for (int i = 0; i < contentTypes.length; i++) {
       String[] protocols =
           Manager.getSupportedProtocols(contentTypes[i]);
       for (int j = 0; j < protocols.length; j++) {
         StringItem si = new StringItem(contentTypes[i] + ": ",
             protocols[j]);
         //si.setLayout(Item.LAYOUT_NEWLINE_AFTER);
         mInformationForm.append(si);
       }
     }
     Command exitCommand = new Command("Exit", Command.EXIT, 0);
     mInformationForm.addCommand(exitCommand);
     mInformationForm.setCommandListener(this);
   }
   
   Display.getDisplay(this).setCurrent(mInformationForm);
 }
 
 public void pauseApp() {}
 public void destroyApp(boolean unconditional) {}
 
 public void commandAction(Command c, Displayable s) {
   notifyDestroyed();
 }

}


      </source>
   
  
 
  



Piano MIDlet

   <source lang="java">

/* Wireless Java 2nd edition Jonathan Knudsen Publisher: Apress ISBN: 1590590775

  • /

import javax.microedition.media.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; public class PianoMIDlet

   extends MIDlet {
 public void startApp() {
   Displayable d = new PianoCanvas();
   
   d.addCommand(new Command("Exit", Command.EXIT, 0));
   d.setCommandListener(new CommandListener() {
     public void commandAction(Command c, Displayable s) {
       notifyDestroyed();
     }
   });
   
   Display.getDisplay(this).setCurrent(d);
 }
 
 public void pauseApp() {}
 public void destroyApp(boolean unconditional) {}

} class PianoCanvas extends Canvas {

 private static final int[] kNoteX = {
    0, 11, 16, 29, 32, 48, 59, 64, 76, 80, 93, 96
 };
 
 private static final int[] kNoteWidth = {
   16,  8, 16,  8, 16, 16,  8, 16,  8, 16,  8, 16
 };
 
 private static final int[] kNoteHeight = {
   96, 64, 96, 64, 96, 96, 64, 96, 64, 96, 64, 96
 };
 
 private static final boolean[] kBlack = {
   false, true, false, true, false,
       false, true, false, true, false, true, false
 };
 
 private int mMiddleCX, mMiddleCY;
 
 private int mCurrentNote;
 
 public PianoCanvas() {
   int w = getWidth();
   int h = getHeight();
   
   int fullWidth = kNoteWidth[0] * 8;
   mMiddleCX = (w - fullWidth) / 2;
   mMiddleCY = (h - kNoteHeight[0]) / 2;
   
   mCurrentNote = 60;
 }
 
 public void paint(Graphics g) {
   int w = getWidth();
   int h = getHeight();
   
   g.setColor(0xffffff);
   g.fillRect(0, 0, w, h);
   g.setColor(0x000000);
   
   for (int i = 60; i <= 72; i++)
     drawNote(g, i);
   
   drawSelection(g, mCurrentNote);
 }
 
 private void drawNote(Graphics g, int note) {
   int n = note % 12;
   int octaveOffset = ((note - n) / 12 - 5) * 7 * kNoteWidth[0];
   int x = mMiddleCX + octaveOffset + kNoteX[n];
   int y = mMiddleCY;
   int w = kNoteWidth[n];
   int h = kNoteHeight[n];
   
   if (isBlack(n))
     g.fillRect(x, y, w, h);
   else
     g.drawRect(x, y, w, h);
 }
 
 private void drawSelection(Graphics g, int note) {
   int n = note % 12;
   int octaveOffset = ((note - n) / 12 - 5) * 7 * kNoteWidth[0];
   int x = mMiddleCX + octaveOffset + kNoteX[n];
   int y = mMiddleCY;
   int w = kNoteWidth[n];
   int h = kNoteHeight[n];
   
   int sw = 6;
   int sx = x + (w - sw) / 2;
   int sy = y + h - 8;
   g.setColor(0xffffff);
   g.fillRect(sx, sy, sw, sw);
   g.setColor(0x000000);
   g.drawRect(sx, sy, sw, sw);
   g.drawLine(sx, sy, sx + sw, sy + sw);
   g.drawLine(sx, sy + sw, sx + sw, sy);
 }
 
 private boolean isBlack(int note) {
   return kBlack[note];
 }
 
 public void keyPressed(int keyCode) {
   int action = getGameAction(keyCode);
   switch (action) {
     case LEFT:
       mCurrentNote--;
       if (mCurrentNote < 60)
         mCurrentNote = 60;
       repaint();
       break;
     case RIGHT:
       mCurrentNote++;
       if (mCurrentNote > 72)
         mCurrentNote = 72;
       repaint();
       break;
     case FIRE:
       try { Manager.playTone(mCurrentNote, 1000, 100); }
       catch (MediaException me) {}
       break;
     default:
       break;
   }
 }

}


      </source>
   
  
 
  



Sound Alert

   <source lang="java">

/*--------------------------------------------------

  • SoundAlert.java
  • Example from the book: Core J2ME Technology
  • Copyright John W. Muchow http://www.CoreJ2ME.ru
  • You may use/modify for any non-commercial purpose
  • -------------------------------------------------*/

import javax.microedition.midlet.*; import javax.microedition.lcdui.*; public class SoundAlert extends MIDlet implements ItemStateListener, CommandListener {

 private Display display;      // Reference to display object 
 private Form fmMain;         // Main form
 private Command cmExit;      // Command to exit the MIDlet
 private ChoiceGroup cgSound; // Choice group
 public SoundAlert()
 {
   display = Display.getDisplay(this);
   // Create an exclusive (radio) choice group
   cgSound = new ChoiceGroup("Choose a sound", Choice.EXCLUSIVE);
   
   // Append options, with no associated images
   cgSound.append("Info", null);    
   cgSound.append("Confirmation", null);    
   cgSound.append("Warning", null);            
   cgSound.append("Alarm", null);        
   cgSound.append("Error", null);    
   cmExit = new Command("Exit", Command.EXIT, 1);
   // Create Form, add components, listen for events
   fmMain = new Form("");
   fmMain.append(cgSound);
   fmMain.addCommand(cmExit);
   fmMain.setCommandListener(this);   
   fmMain.setItemStateListener(this);
 }
 public void startApp()
 {
   display.setCurrent(fmMain);
 }
 public void pauseApp()
 { }
 
 public void destroyApp(boolean unconditional)
 { }
 public void commandAction(Command c, Displayable s)
 {
   if (c == cmExit)
   {
     destroyApp(false);
     notifyDestroyed();
   } 
 }
 
 public void itemStateChanged(Item item)              
 {
   switch (cgSound.getSelectedIndex())
   {
     case 0: 
       AlertType.INFO.playSound(display);
       break;
     case 1:
       AlertType.CONFIRMATION.playSound(display);
       break;
     case 2:
       AlertType.WARNING.playSound(display);
       break;
     case 3:
       AlertType.ALARM.playSound(display);
       break;
     case 4:
       AlertType.ERROR.playSound(display);
       break;
   }
 }

}

      </source>
   
  
 
  



Tone MIDlet

   <source lang="java">

/* Wireless Java 2nd edition Jonathan Knudsen Publisher: Apress ISBN: 1590590775

  • /

import java.io.*; import javax.microedition.io.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.*; import javax.microedition.media.*; import javax.microedition.media.control.*; public class ToneMIDlet extends MIDlet implements CommandListener {

 private final static String kSoundOfMusic = "Sound of Music";
 private final static String kQuandoMenVo = "Quando men vo";
 private final static String kTwinkle = "Twinkle number VII";
 
 private Display mDisplay;
 private List mMainScreen;
 
 public void startApp() {
   mDisplay = Display.getDisplay(this);
   
   if (mMainScreen == null) {
     mMainScreen = new List("AudioMIDlet", List.IMPLICIT);
 
     mMainScreen.append(kSoundOfMusic, null);
     mMainScreen.append(kQuandoMenVo, null);
     mMainScreen.append(kTwinkle, null);
     mMainScreen.addCommand(new Command("Exit", Command.EXIT, 0));
     mMainScreen.addCommand(new Command("Play", Command.SCREEN, 0));
     mMainScreen.setCommandListener(this);
   }
   mDisplay.setCurrent(mMainScreen);
 }
 public void pauseApp() {}
 public void destroyApp(boolean unconditional) {}
 
 public void commandAction(Command c, Displayable s) {
   if (c.getCommandType() == Command.EXIT) notifyDestroyed();
   else run();
 }
 public void run() {
   String selection = mMainScreen.getString(
       mMainScreen.getSelectedIndex());
   
   byte[] sequence = null;
   if (selection.equals(kSoundOfMusic)) {
     sequence = new byte[] {
       ToneControl.VERSION, 1,
       67, 16, // The
       69, 16, // hills
       67,  8, // are
       65,  8, // a -
       64, 48, // live
       62,  8, // with
       60,  8, // the
       59, 16, // sound
       57, 16, // of
       59, 32, // mu -
       59, 32  // sic
     };
   }
   else if (selection.equals(kQuandoMenVo)) {
     sequence = new byte[] {
       ToneControl.VERSION, 1,
       ToneControl.TEMPO, 22,
       ToneControl.RESOLUTION, 96,
       64, 48, ToneControl.SILENCE, 8, 52, 4, 56, 4, 59, 4, 64, 4,
       63, 48, ToneControl.SILENCE, 8, 52, 4, 56, 4, 59, 4, 63, 4,
       61, 72,
       ToneControl.SILENCE, 12, 61, 12,
           63, 12, 66, 2, 64, 10, 63, 12, 61, 12,
       64, 12, 57, 12, 57, 48,
       ToneControl.SILENCE, 12, 59, 12,
           61, 12, 64, 2, 63, 10, 61, 12, 59, 12,
       63, 12, 56, 12, 56, 48,
     };
   }
   else if (selection.equals(kTwinkle)) {
     sequence = new byte[] {
       ToneControl.VERSION, 1,
       ToneControl.TEMPO, 22,
       ToneControl.BLOCK_START, 0,
       60, 8,        62, 4, 64, 4, 65, 4, 67, 4, 69, 4, 71, 4,
       72, 4, 74, 4, 76, 4, 77, 4, 79, 4, 81, 4, 83, 4, 84, 4,
       83, 4, 81, 4, 80, 4, 81, 4, 86, 4, 84, 4, 83, 4, 81, 4,
       81, 4, 79, 4, 78, 4, 79, 4, 60, 4, 79, 4, 88, 4, 79, 4,
       57, 4, 77, 4, 88, 4, 77, 4, 59, 4, 77, 4, 86, 4, 77, 4,
       56, 4, 76, 4, 86, 4, 76, 4, 57, 4, 76, 4, 84, 4, 76, 4,
       53, 4, 74, 4, 84, 4, 74, 4, 55, 4, 74, 4, 83, 4, 74, 4,
       84, 16, ToneControl.SILENCE, 16,
       ToneControl.BLOCK_END, 0,
       ToneControl.BLOCK_START, 1,
       79, 4, 84, 4, 88, 4, 86, 4, 84, 4, 83, 4, 81, 4, 79, 4,
       77, 4, 76, 4, 74, 4, 72, 4, 71, 4, 69, 4, 67, 4, 65, 4,
       64, 8,        76, 8,        77, 8,        78, 8,
       79, 12,              76, 4, 74, 8, ToneControl.SILENCE, 8,
       ToneControl.BLOCK_END, 1,
       
       ToneControl.SET_VOLUME, 100, ToneControl.PLAY_BLOCK, 0,
       ToneControl.SET_VOLUME,  50, ToneControl.PLAY_BLOCK, 0,
       ToneControl.SET_VOLUME, 100, ToneControl.PLAY_BLOCK, 1,
       ToneControl.SET_VOLUME,  50, ToneControl.PLAY_BLOCK, 1,
       ToneControl.SET_VOLUME, 100, ToneControl.PLAY_BLOCK, 0,
     };
   }
   try {
     Player player = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
     player.realize();
     ToneControl tc = (ToneControl)player.getControl("ToneControl");
     tc.setSequence(sequence);
     player.start();
   }
   catch (Exception e) {
     Alert a = new Alert("Exception", e.toString(), null, null);
     a.setTimeout(Alert.FOREVER);
     mDisplay.setCurrent(a, mMainScreen);
   }
 }

}


      </source>