MMAPI (Mobile Media API, JSR 135) 是 Java ME 平台多媒體開發的基石。理解其核心架構——Manager、Player、Control 三大類的職責邊界與協作關係,是高效開發音視頻、錄製、播放功能的前提。本文從架構層面剖析三者交互模型,並解讀關鍵概念:Data Delivery Protocol、Content Types、Media Locator、Media Encoding Strings。
單一職責:管理多媒體數據源,根據數據源創建 Player 實例。
核心靜態方法:
createPlayer(String locator) — 由 Media Locator 創建createPlayer(InputStream stream, String type) — 由流與 Content Type 創建getSupportedContentTypes(String protocol) — 查詢設備支持格式getSupportedProtocols(String contentType) — 反向查詢協議支持生命週期五大狀態(狀態機模型):
realize() 後,資源已就緒(編解碼器、緩衝區等)prefetch() 後,數據預載完成,可即時啟動start() 後,正在播放/錄製close() 後,資源釋放,不可逆關鍵能力:狀態流轉控制、時間基線管理、事件通知(PlayerListener)、Control 獲取入口。
設計模式:策略模式 + 介面隔離。Control 本身是空介面,具體功能由子介面實現:
VideoControl — 視頻顯示模式、縮放、鏡頭參數VolumeControl — 音量調節、靜音ToneControl — 音序播放RecordControl — 錄音/錄像控制FramePositioningControl — 幀級定位(視頻)MetaDataControl — 元數據讀取(ID3 等)獲取方式:player.getControl("VideoControl") 或 player.getControls() 遍歷。
標識數據來源類型,決定 Manager 如何解析 Locator:
| 協議前綴 | 含義 | 典型場景 |
|---|---|---|
file:// | 本地文件系統 | 讀取存儲卡媒體文件 |
https:// / https:// | 網絡流媒體 | 在線音視頻播放 |
capture:// | 設備捕獲設備 | 攝像頭預覽、麥克風錄音 |
rtsp:// | 實時流協議 | 直播流播放 |
device:// | 設備內部數據源 | 鈴聲、系統提示音 |
標識數據格式編碼,指導 Player 選擇解碼器:
audio/mpeg (MP3), audio/amr, audio/wav, audio/midi, audio/mp4video/mpeg, video/3gpp, video/mp4, video/h263image/gif, image/jpeg, image/pngapplication/sdp (會話描述)統一資源標識符,語法:<protocol>://<location>[?<params>]
示例:
capture://video?encoding=video/3gpp&width=176&height=144 — 攝像頭捕獲配置file:///SDCard/video.mp4 — 本地文件絕對路徑https://example.com/stream.m3u8 — HLS 串流地址用於 RecordControl 指定錄製輸出格式,格式為 <content-type>[<params>]。例如:
audio/amr — AMR 錄音video/3gpp?width=320&height=240&framerate=15 — 3GPP 錄像參數化// 1. Manager 根據協議創建 Player
Player p = Manager.createPlayer("capture://video");
// 2. Player 實現化,分配硬件資源
p.realize();
// 3. 獲取 VideoControl 控制預覽顯示
VideoControl vc = (VideoControl) p.getControl("VideoControl");
if (vc != null) {
vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null);
Form form = new Form("Camera");
form.append((Item) vc.initDisplayMode(VideoControl.USE_GUI_PRIMITIVE, null));
Display.getDisplay(this).setCurrent(form);
}
// 4. 啟動預覽
p.start();
// 5. 錄製時動態添加 RecordControl
RecordControl rc = (RecordControl) p.getControl("RecordControl");
rc.setRecordStream(outputStream);
rc.setRecordSizeLimit(maxBytes);
rc.startRecord();
// ...
rc.commit(); // 寫入文件頭
掌握 MMAPI 的「三類四概念」架構模型,能讓開發者從 API 調用者進化為架構設計者:在複雜多媒體場景(如邊下載邊播、多源切換、錄製編碼參數調優)中,能精準定位問題層級,做出最優技術決策。