下邊的代碼描述了如何在J2ME應用裡控制移動設備的音量,VolumeControl類可以用來控制播放器Player類的音量
import Javax.microedition.midlet.*;
import Javax.microedition.lcdui.*;
import Javax.microedition.lcdui.Ticker;
import Javax.microedition.media.*;
public class VolumeControlDemo extends MIDlet implements CommandListener {
private Display display;
private Command exit,incr,decr;
Form frm;
VolumeControl vc;
int vol;
Player player;
public VolumeControlDemo() {
display = Display.getDisplay(this);
}
public void startApp() {
frm=new Form("VolumeControlDemo Demo");
exit= new Command("Exit",Command.EXIT,1);
decr= new Command("Decrease",Command.EXIT,1);
incr= new Command("Increase",Command.EXIT,1);
frm.addCommand(exit);
frm.addCommand(decr);
frm.addCommand(incr);
frm.setCommandListener(this);
display.setCurrent(frm);
try {
// 創建播放器Player對象
player = Manager.createPlayer("/demo.wav");
// 設置循環計數器
player.setLoopCount(-1);
// 播放
player.start();
Control cs[];
// 獲得播放器的所有控制對象
cs = player.getControls();
for (int i = 0; i < cs.length; i++) {
if (cs[i] instanceof VolumeControl)
// 獲得音量控制類實例
vc=(VolumeControl)cs[i];
}
} catch (Exception e) {}
}
public void pauseApp() {
}
public void destroyApp(boolean un) {
}
public void commandAction(Command cmd,Displayable d) {
try {
if(decr) {
if(vol>0) vol--;
vc.setLevel(vol);
} else if() {
if(vol<99) vol--;
vc.setLevel(vol);
}
frm.appent("vol="+vc.getLevel());
}catch(Exception e){}
}
}