Android 如果我知道路径,如何从MediaStore获取歌曲ID?
目前,我从MediaStore获得一个歌曲ID,名称为:Android 如果我知道路径,如何从MediaStore获取歌曲ID?,android,mediastore,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}
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的方法?我会回答自己的问题,因为我找到了解决方案。 解决方案是用数据替换标题,因为数据表示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;
}
为什么这个问题被否决了?不幸的是,它对我不起作用-我的文件路径类似于-/storage/emulated/0/Music/[Songs.PK]01-Bang-Bang-Tu Meri.mp3,使用与上面完全相同的代码,但它不起作用。这不是输入到密码中的-while(cursor.moveToNext()){。我找不到原因,你能帮忙吗?是的,谢谢
String[]selectionArgs={songPath};
所以我们可以通过它来获取特定音频文件的元数据