您的位置:首页 > 其它

支持暂停和继续操作的WAV音频播放

2008-10-14 20:55 501 查看
import java.io.InputStream;

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Graphics;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.midlet.MIDlet;

public class Exec extends MIDlet {
private Display display;
DrawPanel dp = new DrawPanel();

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

public void startApp() {
display.setCurrent(dp);
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}

class DrawPanel extends Canvas {
InputStream in = null;
Player p = null;
int length;
int current = 0;
Thread thread = new Thread(new PlayerUpdater());
boolean flag = false;

public DrawPanel() {
try {
in = getClass().getResourceAsStream("/musics/music.wav");
p = Manager.createPlayer(in, "audio/x-wav");
p.start();
} catch (Exception e) {
System.out.println(e.getMessage());
}

length = (int) (p.getDuration() / 1000 / 1000);
thread.start();
}

protected void paint(Graphics g) {
int width = getWidth();
int height = getHeight();
g.setColor(255, 255, 255);
g.fillRect(0, 0, width, height);
g.setColor(0, 0, 0);
g.fillRect(width / 4, height / 4,
(int) (width / 2 * current / (double) length), 20);
}

// 新增一个线程处理进度条,定义一个内部类
class PlayerUpdater implements Runnable {
public void run() {
try {
while (true) {
if (flag) {
Thread.sleep(1000);
current++;
repaint();
if (current >= length)
break;
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

protected void showNotify() {
flag = true;
try {
p.prefetch();
p.setMediaTime(current * 1000 * 1000L);
p.start();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}

protected void hideNotify() {
try {
p.stop();
} catch (Exception e) {
System.out.println(e.getMessage());
}
flag = false;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐