source code

  1. package com.ociweb.midp2;
  2.  
  3. import java.io.IOException;
  4.  
  5. import javax.microedition.lcdui.Display;
  6. import javax.microedition.lcdui.Form;
  7. import javax.microedition.media.Manager;
  8. import javax.microedition.media.MediaException;
  9. import javax.microedition.media.Player;
  10. import javax.microedition.media.PlayerListener;
  11. import javax.microedition.media.control.ToneControl;
  12. import javax.microedition.midlet.MIDlet;
  13. import javax.microedition.midlet.MIDletStateChangeException;
  14.  
  15. public class PlayToneSequenceMIDlet extends MIDlet implements PlayerListener {
  16. private byte TEMPO = 30;
  17. private byte volume = 100;
  18. private byte d = 8; // eighth note
  19.  
  20. private byte C = ToneControl.C4;
  21. private byte D = (byte) (C + 2); // a whole step
  22. private byte E = (byte) (C + 4); // a major third
  23.  
  24.  
  25. private Player p;
  26. private ToneControl c;
  27. private Form form = new Form("Now Playing");
  28.  
  29. protected void startApp() throws MIDletStateChangeException {
  30. Display.getDisplay(this).setCurrent(form);
  31. try {
  32. play();
  33. } catch (IOException e) {
  34. e.printStackTrace();
  35. } catch (MediaException e) {
  36. e.printStackTrace();
  37. }
  38. }
  39.  
  40. private void play() throws IOException, MediaException {
  41. form.append("Quiet!");
  42. p = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
  43. p.addPlayerListener(this);
  44. p.realize();
  45. c = (ToneControl) p.getControl("ToneControl");
  46. c.setSequence(createSequence());
  47. p.start();
  48. }
  49. private byte[] createSequence() {
  50. byte[] sequence = {
  51. ToneControl.VERSION, 1, // version 1
  52. ToneControl.TEMPO, TEMPO, // set tempo
  53. ToneControl.SET_VOLUME, volume,
  54. ToneControl.BLOCK_START, 0, // Define block 0
  55. C, d, D, d, E, d, // Define repeatable block of 3 eighth notes
  56. ToneControl.BLOCK_END, 0, // End block 0
  57. ToneControl.PLAY_BLOCK, 0, // play block 0
  58. ToneControl.SILENCE, d, E, d, D, d, C, d, // play some other notes
  59. ToneControl.PLAY_BLOCK, 0, // play block 0 again
  60. };
  61. return sequence;
  62. }
  63. public void playerUpdate(Player player, String event, Object eventData) {
  64. p.close(); // release the resources
  65. if (event == PlayerListener.END_OF_MEDIA && volume > 10) {
  66. try {
  67. volume /= 2;
  68. play();
  69. } catch (IOException e1) {
  70. e1.printStackTrace();
  71. } catch (MediaException e) {
  72. e.printStackTrace();
  73. }
  74. } else if (volume < 10) {
  75. notifyDestroyed();
  76. }
  77. }
  78. protected void pauseApp() {}
  79.  
  80. protected void destroyApp(boolean unconditional)
  81. throws MIDletStateChangeException {}
  82. }
secret