下面的代码是针对E680i编写的,并且在真机运行成功,程序首先探测了E680i的多媒体支持能力,并且把所有支持的格式显示到屏幕,由于不能一屏完全显示,因此设置了滚动;当滚动到底部或者顶部时,会播放一段乐音序列。
该程序可以作为学习声音的入门参考。
/*
* MainCanvas.java
*
* Created on 2006年8月18日, 下午3:28
*
*/
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.ToneControl;
/**
*
* @author mydeman
*/
public class MainCanvas extends Canvas{
private Midlet midlet;
private int index = 0;
private int line = 0;
//每行字体的高度
private static int lineHeight = Font.getDefaultFont().getHeight();
//所有支持的类型
private static String[] allTypes;
//音调
private static byte C4 = ToneControl.C4;
private static byte E4 = (byte)(C4 + 2);
private static byte D4 = (byte)(C4 + 1);
private static byte G4 = (byte)(C4 + 4);
private static byte rest = ToneControl.SILENCE;
//播放器
private static Player player;
//声明声音序列,该序列出自《J2ME手机游戏编程入门》
private static byte[] marylambSequence = {
ToneControl.VERSION, 1,
ToneControl.TEMPO, 30,
ToneControl.BLOCK_START, 0,
E4,8, D4,8, C4,8, D4,8,
E4,8, E4,8, E4,8, rest, 8,
ToneControl.BLOCK_END, 0,
ToneControl.PLAY_BLOCK, 0,
D4,8, D4,8, D4,8, rest,8,
E4,8, G4,8, G4,8, rest,8,
ToneControl.PLAY_BLOCK, 0,
D4,8, D4,8, E4,8, D4,8, C4,8
};
/** Creates a new instance of MainCanvas */
public MainCanvas(Midlet midlet) {
this.midlet = midlet;
setFullScreenMode(true);
init();
}
private void init() {
try {
//初始化播放器
player = Manager.createPlayer(Manager.TONE_DEVICE_LOCATOR);
player.realize();
//创建播放序列
ToneControl toneControl = (ToneControl)player.getControl("ToneControl");
toneControl.setSequence(marylambSequence);
} catch (Exception e) {
}
//得到总行数和所有支持的类型
line = 310 / lineHeight;
allTypes = Manager.getSupportedContentTypes(null);
}
/**
* 绘制屏幕
*/
protected void paint(Graphics g) {
//绘制背景
g.setColor(0, 0, 0);
g.fillRect(0, 0, 240, 320);
//绘制当前屏幕上的支持类型
g.setColor(0, 255, 0);
for(int i = 0; i < line; i++) {
g.drawString(allTypes[i + index], 10, i * lineHeight + 10,
Graphics.TOP|Graphics.LEFT);
}
}
/**
* 按键事件处理
*/
public void keyPressed(int keyCode) {
switch(getGameAction(keyCode)) {
//如果按键为A,则退出程序
case Canvas.GAME_A :
player.close();
midlet.notifyDestroyed();
break;
//如果按键为UP,则向上滚动
case Canvas.UP :
scroll(1);
break;
//如果按键为DOWN,则向下滚动
case Canvas.DOWN :
scroll(-1);
break;
}
}
/**
* 设置屏幕滚动
*/
private void scroll(int i) {
//设置索引
index += i;
//判断索引的大小,如果已经到达了底部或者顶部,则
//播放预先定义好的乐音序列
if(index < 0) {
index = 0;
playSound();
} else if(index + line > allTypes.length) {
index -= i;
playSound();
}
//重绘屏幕
repaint();
serviceRepaints();
}
/**
* 播放声音
*/
private void playSound() {
try {
player.start();
} catch(Exception e) {
}
}
}