Senin, 16 Juni 2008

Memainkan Tone

ToneCanvas.java

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


class ToneCanvas extends Canvas implements CommandListener {
private Command cmExit;
private String keyText = null;
private static final int minNote = 0;
private static final int maxNote = 127;
private int note = ToneControl.C4;
private PlayTone midlet;
private Display display;
private String[] tone = new String[]{"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"};
private int index = 0;

public ToneCanvas(PlayTone midlet, Display display){
this.midlet = midlet;
this.display = display;
cmExit = new Command("Exit", Command.EXIT, 1);
addCommand(cmExit);
setCommandListener(this);
}

protected void paint(Graphics g){
g.setColor(255, 255, 255);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0, 0, 0);
g.drawString("Note : " + tone[index] + " Value : " + Integer.toString(note), getWidth()/2, getHeight()/2, Graphics.TOP
| Graphics.HCENTER);
}

public void commandAction(Command c, Displayable d){
if (c == cmExit)
midlet.exitMIDlet();
}

protected void keyPressed(int keyCode){
switch (keyCode){
case -5:
note = ToneControl.C4;
break;
case -4:
if (note != maxNote){
note++;
if(index < (tone.length - 1)){
index++;
}else{
index = 0;
}
}
break;
case -3:
if (note != minNote){
note--;
if(index > 0){
index--;
}else{
index = tone.length - 1;
}
}
break;
case 49:
note = 60;
index = 0;
break;
case 50:
note = 62;
index = 2;
break;
case 51:
note = 64;
index = 4;
break;
case 52:
note = 65;
index = 5;
break;
case 53:
note = 67;
index = 7;
break;
case 54:
note = 69;
index = 9;
break;
case 55:
note = 71;
index = 11;
break;
default :
break;
}
playNote();
repaint();
}

private void playNote(){
try {
Manager.playTone(note, 300, 100);
}catch (Exception e){
Alert alr = new Alert("Error", "Tone tidak dapat dimainkan", null, AlertType.ERROR);
alr.setTimeout(Alert.FOREVER);
display.setCurrent(alr, this);
}
}
}

PlayTone.java

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class PlayTone
extends MIDlet{

private Display display;
private ToneCanvas canvas;

public PlayTone() {
display = Display.getDisplay(this);
}


public void startApp() {
canvas = new ToneCanvas(this, display);
display.setCurrent(canvas);
}

public void pauseApp() {}

public void destroyApp(boolean unconditional) {
}

public void exitMIDlet() {
destroyApp(false);
notifyDestroyed();
}
}

Tidak ada komentar: