十一月's profileNOVEMBREBlogListsGuestbookMore ![]() | Help |
|
|
March 23 一个音乐播放的工具类 //引入媒体包 import javax.microedition.media.*; //引入控制包 import javax.microedition.media.control.*; //读取资源使用 import java.io.*; public class LPAudioPlayer { /** 媒体接口 */ private Player player; /** 播放的媒体文件名 */ private String filename; /** 播放的媒体格式 */ private String format; /** * 媒体播放类构造方法 * * @param filename传入媒体的文件名 * @param format文件格式 * @param isLoad是否立刻装载媒体 */ public LPAudioPlayer(String filename, String format, boolean isLoad) { this.format = format; this.filename = filename; if (isLoad) { loadResource(); } } /** * 媒体构造方法 * * @param filename文件名称 * @param format文件格式 */ public LPAudioPlayer(String filename, String format) { this.format = format; this.filename = filename; } /** * 装载媒体资源 * */ public void loadResource() { try { // 根据文件名称创建流对象 InputStream is = getClass().getResourceAsStream("/" + filename); // 创建播放器接口 player = Manager.createPlayer(is, format); } catch (IOException e) { System.out.println("can't load " + filename); System.out.println(e); } catch (MediaException e) { System.out.println("can't create audio"); System.out.println(e); } } /** * 设置循环播放 * */ public void setLoop() { if (player != null) { player.setLoopCount(-1); } } /** * 设置音量 * * @param level音量大小 */ public void setVolume(int level) { if (player != null) { VolumeControl control = (VolumeControl) player .getControl("VolumeControl"); control.setLevel(level); } } /** * 停止播放 * */ public void stop() { if (player != null) { try { player.stop(); } catch (MediaException e) { System.out.println("can't stop audio"); System.out.println(e); } } } /** * 播放方法 * */ public void play() { if (player != null) { try { // 获得播放信息 player.realize(); // 获取稀有资源 player.prefetch(); // 开始播放 player.start(); } catch (MediaException e) { System.out.println("can't play audio"); System.out.println(e); } } } /** * 重新播放声音文件 * */ public void replay() { // 关闭当前声音接口 close(); // 进行垃圾回收 System.gc(); loadResource(); play(); } public void close() { if (player != null) { player.close(); player = null; } } } 使用方法// 创建播放声音对象 LPAudioPlayer mid = new LPAudioPlayer("back.mid", "audio/midi", true); // 设置循环播放 mid.setLoop(); // 播放音乐 mid.play(); 转]查询手机支持的所有声音、视频文件格式的小代码网上抓来的,也许有些朋友能用得到。 import javax.microedition.lcdui.*;
|
|
|