我想要手机中的歌曲封面专辑,但我得到了colum index -1
int imageColumn = musicCursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM_ART);
这是完整的代码:
// Retrieve song info from device
public void getSongList() {
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
// Query external audio
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, selection, null, null);
// Iterate over results if valid
if (musicCursor != null && musicCursor.moveToFirst()) {
// Get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int durationColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media.DURATION);
int imageColumn = musicCursor.getColumnIndex
(MediaStore.Audio.AlbumColumns.ALBUM_ART);
// ****** HERE I HAVE -1, the same is with MediaStore.Audio.Albums.ALBUM_ART ******
// Add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
long thisDuration = musicCursor.getLong(durationColumn);
String thisPathAlbumImage = musicCursor.getString(imageColumn);
// ****** HERE MY APP CRASH FOR -1 INDEX ******
arrayOfSongs.add(new Song(thisId, thisTitle, thisArtist, thisDuration, thisPathAlbumImage));
Log.d(LOG_TAG, "New song added: " + thisTitle);
}
while (musicCursor.moveToNext());
}
}
为什么我得到-1?我希望每个专辑封面都能在ListView中设置歌曲标题,艺术家姓名和持续时间。
答案 0 :(得分:1)
您应该使用Uri.parse("content://media/external/audio/albumart");
来查询albumart。您可以在this StackOverflow post.
答案 1 :(得分:1)
您正在使用的查询不会返回列MediaStore.Audio.AlbumColumns.ALBUM_ART
。你现在有一些选择。
MediaStore.Audio.Albums.EXTERNAL_CONTENT_TYPE
将检索相册列表,并包含MediaStore.Audio.AlbumColumns.ALBUM_ART
。请注意,此选项不会加载任何音乐,您需要单独查询。以下是一些实施选项2的示例代码。
Bitmap art;
String path;
Uri artUri;
Uri musicUri = android.provider.MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI;
.
.
.
path = musicCursor.getString(imageColumn);
if (path != null) {
artUri = Uri.fromFile(new File(path));
try {
coverArt = MediaStore.Images.Media.getBitmap(musicResolver, artUri);
} catch (IOException e) {
// For some reason we have no album art. Assign a default cover?
e.printStackTrace();
}
}