Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 音樂播放器實作:用 MediaStore 打造歌曲列表與專輯封面

編輯:關於 Android 程式設計

要做一個音樂播放器的第一個畫面,通常就是「歌曲清單」。好消息是 Android 內建的媒體掃描機制已經把 SD 卡與內部儲存中的音訊整理成資料庫,透過 MediaStore 就能直接取到歌名、歌手、時長、專輯資訊,不必自己遞迴搜尋檔案系統。

一、列表版面配置

先用最簡單的 ListView 把清單框起來,記得加上 cacheColorHint="#00000000",讓自訂背景在捲動時不會出現黑影:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <ListView
        android:id="@+id/music_list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@drawable/listbg"
        android:cacheColorHint="#00000000" />

</LinearLayout>

二、用 MediaStore 取出歌曲資料

整個流程可以拆成兩步:先查詢資料庫拿到 Cursor,再自訂 Adapter 把資料渲染到每一列。

public class SongsActivity extends Activity {

    private ListView listView;
    private Cursor cursor;
    private MusicListAdapter musicListAdapter;

    /** 要查詢的欄位:標題、時長、歌手、ID、顯示名稱、路徑、專輯ID */
    private static final String[] MUSIC_INFO = new String[] {
        MediaStore.Audio.Media.TITLE,
        MediaStore.Audio.Media.DURATION,
        MediaStore.Audio.Media.ARTIST,
        MediaStore.Audio.Media._ID,
        MediaStore.Audio.Media.DISPLAY_NAME,
        MediaStore.Audio.Media.DATA,
        MediaStore.Audio.Media.ALBUM_ID
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_songs);
        listView = (ListView) findViewById(R.id.music_list);
        listView.setOnItemClickListener(new MusicListOnClickListener());
        showMusicList();
    }

    private void showMusicList() {
        cursor = getContentResolver().query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                MUSIC_INFO, null, null,
                MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

        musicListAdapter = new MusicListAdapter(this, cursor);
        listView.setAdapter(musicListAdapter);
        listView.setOnCreateContextMenuListener(new ContextMenuListener());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 回到主畫面前記得回收注册的廣播接收器
            finish();
        }
        return true;
    }
}

如果清單裡還需要用到「目前播放位置」這類狀態,可以另外用 int[] _ids、String[] _titles、String[] _artists 把常用欄位快取成陣列,避免在 Adapter 中反覆 moveToPosition。不過更直覺的做法是直接在 Adapter 內操作 Cursor。

三、自訂 Adapter:把歌名、歌手、封面填進每一列

public class MusicListAdapter extends BaseAdapter {

    private Context myContext;
    private Cursor myCursor;
    private int pos = -1;   // 目前播放中的項目位置

    public MusicListAdapter(Context context, Cursor cursor) {
        myContext = context;
        myCursor = cursor;
    }

    @Override public int getCount() { return myCursor.getCount(); }
    @Override public Object getItem(int position) { return position; }
    @Override public long getItemId(int position) { return position; }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        View vi = convertView;
        if (convertView == null) {
            holder = new ViewHolder();
            vi = LayoutInflater.from(myContext).inflate(R.layout.musiclist, null);
            holder.tv_music = (TextView) vi.findViewById(R.id.music1);
            holder.tv_singer = (TextView) vi.findViewById(R.id.singer);
            holder.tv_time = (TextView) vi.findViewById(R.id.time);
            holder.img = (ImageView) vi.findViewById(R.id.listitem);
            vi.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        myCursor.moveToPosition(position);

        // 標題太長就截斷加省略號
        String title = myCursor.getString(0).trim();
        holder.tv_music.setText(title.length() > 15
                ? title.substring(0, 12) + "..."
                : title);

        // 未知歌手
        String artist = myCursor.getString(2);
        holder.tv_singer.setText("".equals(artist) ? "未知藝術家" : artist);

        // 時長格式化
        holder.tv_time.setText(toTime(myCursor.getInt(1)));

        if (position == pos) {
            holder.img.setImageResource(R.drawable.isplaying);
        } else {
            Bitmap bm = getArtwork(myContext,
                    myCursor.getInt(3),
                    myCursor.getInt(myCursor.getColumnIndex(
                            MediaStore.Audio.Media.ALBUM_ID)), true);
            holder.img.setImageBitmap(bm);
        }
        return vi;
    }

    public void setItemIcon(int position) { pos = position; }

    /** 毫秒轉 mm:ss */
    public String toTime(int time) {
        time /= 1000;
        int minute = time / 60;
        int second = time % 60;
        return String.format("%02d:%02d", minute, second);
    }

    static class ViewHolder {
        TextView tv_music, tv_singer, tv_time;
        ImageView img;
    }
}

ViewHolder 搭配 setTag 是 ListView 效能的關鍵:避免每一列被繪製時重複 findViewById,長清單捲動明顯順暢。

四、取得內嵌專輯封面

封面是這份程式最麻煩的部分。內嵌圖片不在檔案系統裡,得透過 content://media/external/audio/albumart 這個 URI 向 MediaStore 索取;若已取得過的縮圖被清掉,還要回頭從原始音訊檔解析。

private static final Uri sArtworkUri =
        Uri.parse("content://media/external/audio/albumart");

public static Bitmap getArtwork(Context context, long song_id,
                                long album_id, boolean allowdefault) {
    if (album_id < 0) {
        // 不在媒體資料庫中,直接從檔案取
        if (song_id >= 0) {
            Bitmap bm = getArtworkFromFile(context, song_id, -1);
            if (bm != null) return bm;
        }
        return allowdefault ? getDefaultArtwork(context) : null;
    }

    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri == null) return null;

    InputStream in = null;
    try {
        // 先量尺寸,再決定縮放比例,避免大圖直接吃爆記憶體
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        in = res.openInputStream(uri);
        BitmapFactory.decodeStream(in, null, options);

        options.inSampleSize = computeSampleSize(options, 30);
        options.inJustDecodeBounds = false;
        options.inDither = false;
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        in = res.openInputStream(uri);
        return BitmapFactory.decodeStream(in, null, options);
    } catch (FileNotFoundException ex) {
        // 縮圖不存在,退回原始檔案解析
        Bitmap bm = getArtworkFromFile(context, song_id, album_id);
        if (bm != null && bm.getConfig() == null) {
            bm = bm.copy(Bitmap.Config.RGB_565, false);
        }
        if (bm == null && allowdefault) bm = getDefaultArtwork(context);
        return bm;
    } finally {
        if (in != null) {
            try { in.close(); } catch (IOException ignored) {}
        }
    }
}

static int computeSampleSize(BitmapFactory.Options options, int target) {
    int w = options.outWidth;
    int h = options.outHeight;
    int candidate = Math.max(w / target, h / target);
    if (candidate == 0) return 1;
    if (candidate > 1 && w > target && w / candidate < target) candidate -= 1;
    if (candidate > 1 && h > target && h / candidate < target) candidate -= 1;
    return candidate;
}

private static Bitmap getDefaultArtwork(Context context) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inPreferredConfig = Bitmap.Config.RGB_565;
    return BitmapFactory.decodeStream(
            context.getResources().openRawResource(R.drawable.item), null, opts);
}

若要從原始檔案取,則用 openFileDescriptor 打開 content://media/external/audio/media/<songid>/albumart,再以 BitmapFactory.decodeFileDescriptor 解碼,同樣先 inJustDecodeBounds = true 量一次尺寸再決定 inSampleSize。

實作提醒

  • 記得在清單中保留一個 mCachedBit 之類的靜態快取,同一張封面不要每捲一次就解碼一次。
  • 大量解碼封面會造成 GC 抖動,實務上可加上 LruCache 做記憶體快取。
  • 别忘了在 onDestroy 中關閉 Cursor,並在返回上一頁時反註冊掃描廣播接收器,避免記憶體洩漏。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved