Как получить песню (AlbumArt) из внутренней и внешней памяти устройства?

Я пытаюсь сделать приложение для музыкального проигрывателя.

Мне нужен список с изображением песни, названием песни и именем исполнителя.

Что-то вроде этого.

введите здесь описание изображения

Я выяснил songName и songTitle с помощью Content Resolver, но я не знаю, как отобразить соответствующее изображение этой песни.

Вот мой ListSong.java, который используется для извлечения песен с устройства.

public class ListSong extends Fragment {

    private ArrayList<Song> songList;
    private ListView songView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.listsongs, container, false);

        songView = (ListView)rootView.findViewById(R.id.songsList);
        songList = new ArrayList<Song>();

        getSongList();

        SongAdapter songAdt = new SongAdapter(getActivity(), songList);
        songView.setAdapter(songAdt);

        return rootView;

    }

    public void getSongList(){
        ContentResolver musicResolver = getActivity().getContentResolver();
        Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
        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);
            //add songs to list
            do {
                long thisId = musicCursor.getLong(idColumn);
                String thisTitle = musicCursor.getString(titleColumn);
                String thisArtist = musicCursor.getString(artistColumn);
                songList.add(new Song(thisId, thisTitle, thisArtist));
            }
            while (musicCursor.moveToNext());
        }
    }

}

Вот мой класс SongInfo(Song.java)

public class Song {

    private long id;
    private String title;
    private String artist;

    public Song(long songID, String songTitle, String songArtist) {
        this.id = songID;
        this.title = songTitle;
        this.artist = songArtist;
    }

    public long getID(){return id;}
    public String getTitle(){return title;}
    public String getArtist(){return artist;}

}

Я просто хочу узнать, есть ли какой-нибудь способ получить соответствующие песни для их песен.


person Aditya Verma    schedule 18.10.2017    source источник


Ответы (1)


Попробуйте использовать следующий код, чтобы получить Song Art:

ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
int albumIDColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID);
long thisAlbumID = musicCursor.getLong(albumIDColumn);
Cursor cursor = musicResolver.query(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
                        new String[]{MediaStore.Audio.Albums._ID, MediaStore.Audio.Albums.ALBUM_ART},
                        MediaStore.Audio.Albums._ID + "=?",
                        new String[]{String.valueOf(thisAlbumID)},
                        null);          
String imagePath = "";
if (cursor.moveToFirst()) {
    imagePath = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART));
}
person Gaurav    schedule 18.10.2017
comment
Должен ли я также редактировать класс песни, потому что он хранит информацию о песне. - person Aditya Verma; 18.10.2017
comment
да, вам нужно изменить класс bean-компонента, поскольку добавлен один новый параметр. - person Gaurav; 18.10.2017
comment
Эй, извините за беспокойство, но я новичок в этом деле, не могли бы вы просто полностью написать код для Content Resolver и класса Song, как я написал в своем вопросе, если у вас есть время. - person Aditya Verma; 18.10.2017
comment
@Aditya Verma, вы должны попробовать сами и опубликовать здесь, если вы где-то застряли. Для этого и создано это сообщество... - person Gaurav; 18.10.2017
comment
После реализации вашего ответа на мой код. Кажется, это не работает. Приложение продолжает падать. Можешь взглянуть на это? Заголовок stackoverflow.com/questions/46811103/ - person Aditya Verma; 19.10.2017