我想要手机里歌曲的封面专辑,但我得到了列索引-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中设置歌曲标题、艺术家姓名和持续时间。
您应该使用Uri.parse("content://media/external/audio/albumart");
来查询白蛋白。您可以在这个StackOverflow帖子中获得更多信息。
您正在使用的查询不会返回列MediaStore.Audio.AlbumColumns.ALBUM_ART
。您现在有了某些选择。
- 您可以使用由@nawako提供并链接的答案。但就这样Ian Lake的推文提醒我们,它并不是官方SDK的一部分,可以更改或修改
- 您可以使用返回列的查询。使用
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();
}
}