目前我正在通过歌曲标题从 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的方法?
最佳答案
自从找到解决方案后,我将回答我自己的问题。
解决方案是用 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;
}
关于android - 如果我知道路径,如何从 MediaStore 获取歌曲 ID?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35394152/