Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

透過 MediaStore 讀取多媒體資訊

編輯:Android 開發實例

透過 Android 的 API,相簿、播放器、錄音、攝影這些功能都能實現。這一主題需要掌握四塊:多媒體 ContentProvider 的調用、Camera、AudioRecord 與 AudioTrack,以及 MediaPlayer。

問題:如何拿到歌曲清單與資訊

PC 上的音樂播放器很輕易就能顯示歌手名、歌曲名、專輯名、年份。在 Android 上呢?

先看看系統提供的 ContentProvider

Android 為常用資料型別(音訊、視訊、圖片、聯絡人等)準備了大量 ContentProvider,定義在 android.provider 套件下。它們實際對應到一個 SQLite 資料庫,位置在:

/data/data/com.android.providers.media/databases/

你可以在 Eclipse 中開啟 File Explorer 視圖(Window → Show View → Other → Android → File Explorer),把 external.db 拉回電腦,用 SQLite 工具(例如 Firefox 的 SQLite Manager 擴充功能)打開來看,會看到幾張關鍵表:

  • audio_meta:管理 SD 卡中的音訊資源。
  • video:管理 SD 卡中的視訊資源。
  • images:管理 SD 卡中的圖片資源。

為什麼要先講這些?

來看一個音樂播放器的典型需求:

  1. 取得音樂檔案清單與路徑。
  2. 取得音樂檔案屬性(歌名、歌手、專輯、年份等)。
  3. 使用者手動刪除記憶卡中的音樂檔後,如何同步更新清單?

如果沒有 Android 經驗,直覺的做法可能是這樣:

  • 用 file.listFile() 掃目錄取得清單。記憶卡檔案一多就特別耗時,讓使用者等個十秒,很可能直接被卸載。
  • 音樂屬性有的寫在檔頭、有的寫在檔尾,必須自行讀位元組解析。雖然有現成的開源 MP3 解析庫,但同樣耗時,上手也要時間。
  • 檔案被手動刪掉後,清單怎麼同步?总不能讓程式隨時去呼叫 file.listFile() 維護吧。

答案:系統早就幫你做完了

觀察模擬器開機時 logcat 輸出的日誌,會看到系統呼叫 MediaScanner 去掃描 Internal 與 External Volume。原來開機時系統會在背景掃描內外存裝置,把多媒體資料寫進資料庫,同時把檔案屬性一併解析好。我們不費吹灰之力就解決了前兩個需求。

讀取 SD 卡中的音樂

public static ArrayList<Song> readDataFromSD(Context context, int component) {
    Cursor cursor = context.getContentResolver().query(
        MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
        new String[] {
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.DISPLAY_NAME,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.YEAR,
            MediaStore.Audio.Media.MIME_TYPE,
            MediaStore.Audio.Media.SIZE,
            MediaStore.Audio.Media.DATA
        },
        MediaStore.Audio.Media.MIME_TYPE + "=? or " + MediaStore.Audio.Media.MIME_TYPE + "=?",
        new String[] { "audio/mpeg", "audio/x-ms-wma" },
        null);

    ArrayList<Song> songs = null;
    if (cursor.moveToFirst()) {
        songs = SongInfoUtil.getList(cursor, context, component);
    }
    return songs;
}

把 Cursor 包裝成資料物件

public class SongInfoUtil {
    public static ArrayList<Song> getList(Cursor cursor, Context mContext, int component) {
        Song song = null;
        ArrayList<Song> list = new ArrayList<Song>();

        do {
            song = new Song();
            song.setFilename(cursor.getString(1));  // 檔名
            song.setTitle(cursor.getString(2));     // 歌曲名
            song.setDuration(cursor.getInt(3));     // 時長
            song.setSinger(cursor.getString(4));    // 歌手
            song.setAlbum(cursor.getString(5));     // 專輯
            song.setYear(cursor.getString(6) != null ? cursor.getString(6) : "未知");

            String mime = cursor.getString(7).trim();
            if ("audio/mpeg".equals(mime)) {
                song.setType("mp3");
            } else if ("audio/x-ms-wma".equals(mime)) {
                song.setType("wma");
            }

            if (cursor.getString(8) != null) {
                float temp = cursor.getInt(8) / 1024f / 1024f;
                song.setSize((temp + "").substring(0, 4) + "M");
            } else {
                song.setSize("未知");
            }

            if (cursor.getString(9) != null) {
                song.setFileUrl(cursor.getString(9));   // 檔案路徑
            }
            list.add(song);
        } while (cursor.moveToNext());

        cursor.close();
        return list;
    }
}

圖片與影片也可以用同樣的方式取得,只是換成 MediaStore.Images 與 MediaStore.Video 的 URI。

第三個需求:手動增刪檔案後如何同步

答案是系統不會自動幫你做。這時候要請出 MediaScanner——但不能直接呼叫它,必須以廣播的形式通知系統去掃描指定的 URI,掃完之後再重新查詢 ContentProvider。

private void scanSdCard() {
    IntentFilter intentFilter = new IntentFilter(
            Intent.ACTION_MEDIA_SCANNER_STARTED);
    intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
    intentFilter.addDataScheme("file");

    registerReceiver(scanReceiver, intentFilter);

    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + getExternalStorageDirectory().getAbsolutePath())));
}

private class ScanSdFilesReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)) {
            // 掃描開始:可以顯示等待框,改善使用者體驗
            scanHandler.sendEmptyMessage(STARTED);
        }
        if (Intent.ACTION_MEDIA_SCANNER_FINISHED.equals(action)) {
            // 掃描結束:關閉等待框並重新查詢 ContentProvider
            scanHandler.sendEmptyMessage(FINISHED);
        }
    }
}

記得在 Activity 銷毀時呼叫 unregisterReceiver() 解除註冊,避免記憶體洩漏。

小結

關鍵觀念只有一句:不要自己掃目錄,交給 MediaStore。系統已經在開機時做好了所有解析工作,你的任務只是「查詢」與「在檔案變動時觸發重新掃描」。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved