MMAPI (JSR 135) 為 Java ME 平台帶來了豐富的多媒體能力,除音視頻播放外,還支持圖像捕獲與播放。本文詳細講解如何利用 MMAPI 直接播放 GIF 動畫文件,省去手動幀切換的繁瑣邏輯,並提供完整可運行的 MIDlet 示例代碼。
播放 GIF 動畫與視頻播放流程高度相似,關鍵差別在於 Content Type 的指定:
image/gif 格式Player 實例:Manager.createPlayer(inputStream, "image/gif")VideoControlUSE_GUI_PRIMITIVE 模式初始化顯示,嵌入 Formprivate void createPlayer(InputStream is) {
String[] supportedTypes = Manager.getSupportedContentTypes(null);
for (String type : supportedTypes) {
if (type.toLowerCase().indexOf("image/gif") != -1) {
try {
player = Manager.createPlayer(is, "image/gif");
player.realize();
} catch (IOException | MediaException e) {
e.printStackTrace();
}
break; // 找到支持即停止檢索
}
}
}
優化提示:實際部署時建議緩存支持格式列表,避免重複調用 getSupportedContentTypes()。
VideoControl vc = (VideoControl) player.getControl("VideoControl");
if (vc != null) {
Form form = new Form("GIF Player");
Item videoItem = (Item) vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
form.append(videoItem);
display.setCurrent(form);
}
public class GifPlayer extends MIDlet {
private Display display;
private Player player;
public void startApp() {
if (display == null) display = Display.getDisplay(this);
Form form = new Form("GIF Player");
InputStream is = getClass().getResourceAsStream("/a.gif");
createPlayer(is);
if (player == null) {
form.append("不支持 image/gif 格式");
} else {
VideoControl vc = (VideoControl) player.getControl("VideoControl");
if (vc != null) {
form.append((Item) vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null));
}
}
display.setCurrent(form);
try { player.start(); }
catch (MediaException e) { e.printStackTrace(); }
}
private void createPlayer(InputStream is) { /* 同上 */ }
public void destroyApp(boolean unconditional) {
if (player != null) {
player.close();
player = null;
}
}
public void pauseApp() {}
}
/a.gif)置於 res 目錄,構建時自動納入 JAR。destroyApp() 中必須調用 player.close() 並置空引用,防止內存洩漏導致應用被系統強殺。IOException(資源讀取失敗)與 MediaException(格式不支持/解碼錯誤),給出針對性用戶提示。同理可播放其他靜態圖片格式(PNG/JPEG),只需將 Content Type 改為 image/png 或 image/jpeg。對於需要交互控制(暫停/跳轉)的場景,可結合 PlayerListener 監聽播放事件實現更豐富的播放器功能。