📄 musiccanvas.java
字号:
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
public class MusicCanvas extends Canvas implements Runnable {
private boolean running = false; // 线程是否在运行
private Player player = null; // Player
static final int VOLUME_LEVEL = 50; // 音量初始化为50
private int volumesetting = VOLUME_LEVEL; // 音量级别
private boolean volumemuted = false; //是否暂停播放了
protected void paint(Graphics g) {
}
public void start() {
running = true;
Thread t = new Thread(this);
t.start();
}
public void run() {
while (running) {
repaint();
try {
Thread.sleep(100);
} catch (InterruptedException ie) {
System.out.println("Thread exception");
}
}
}
public void stop() {
running = false;
if (player != null) {
player.close();
player = null;
}
}
public void playsong() {
try {
// 创建player对象
if (player == null){
InputStream in = getClass().getResourceAsStream("/test-wav.wav");
//指定文件类型
player = Manager.createPlayer(in, "audio/x-wav");
}
player.realize();
// 设置循环播放次数
player.setLoopCount(1);
// 设置音量为50
VolumeControl volume = (VolumeControl) player
.getControl("VolumeControl");
volume.setLevel(VOLUME_LEVEL);
player.start();
} catch (IOException ioe) {
System.out.println("IO Exception!");
} catch (MediaException me) {
System.out.println("Media Exception!");
}
}
protected void keyPressed(int keycode) {
switch (getGameAction(keycode)) {
case LEFT:
adjustvolume(-5, false);
break;
case RIGHT:
adjustvolume(5, false);
break;
case FIRE:
adjustvolume(0, true);
break;
}
}
private void adjustvolume(int increment, boolean mute) {
if (player != null) {
VolumeControl volume = (VolumeControl) player
.getControl("VolumeControl");
if (volume != null) {
// 目前音量级别
volumesetting = volume.getLevel();
// 如果不是消音了,即停止播放了
if (mute != true) {
// 调整音量
volumesetting += increment;
volumesetting = volume.setLevel(volumesetting);
} else {
volume.setMute(!volume.isMuted());
volumemuted = volume.isMuted();
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -