如果我知道路径,如何从MediaStore获取歌曲ID?

时间:2016-02-14 16:32:07

标签: android mediastore

目前,我正在通过歌曲的标题从MediaStore获取歌曲ID:

long id = 0;
    ContentResolver cr = context.getContentResolver();

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.TITLE;
    String[] selectionArgs = {songTitle};
    String[] projection = {MediaStore.Audio.Media._ID};
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

    Cursor cursor = cr.query(uri, projection, selection, selectionArgs, sortOrder);

    if (cursor != null) {
        while (cursor.moveToNext()) {
            int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            id = Long.parseLong(cursor.getString(idIndex));
        }
    }
    return id;

仅当标题不为空时,此方法才有效。 是否可以直接从mp3文件的路径直接从MediaStore获取歌曲ID?

1 个答案:

答案 0 :(得分:4)

自从找到解决方案后,我将回答我自己的问题。 解决方案是用DATA替换TITLE,因为DATA代表MediaStore中媒体文件的路径。

public static long getSongIdFromMediaStore(String songPath, Context context) {
    long id = 0;
    ContentResolver cr = context.getContentResolver();

    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.DATA;
    String[] selectionArgs = {songPath};
    String[] projection = {MediaStore.Audio.Media._ID};
    String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";

    Cursor cursor = cr.query(uri, projection, selection + "=?", selectionArgs, sortOrder);


    Log.d(Constants.LOG_TAG, songPath);
    if (cursor != null) {
        while (cursor.moveToNext()) {
            int idIndex = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            id = Long.parseLong(cursor.getString(idIndex));
        }
    }
    return id;
}