获取到Android设备的本地音乐,并显示音乐的时长,专辑图片,音乐名字以及歌手姓名等。当设备从播放器中下载音乐的时候,这些信息都会存储到设备中。我们获取的时候可以通过设备暴露给我们的ContentProvider接口去查询这些信息。ok,话不多说,上代码。
首先我们要定义一个名字叫Song的bean文件,用来保存歌曲的信息。
public class Song {
public String name;//歌曲名
public String singer;//歌手
public long size;//歌曲所占空间大小
public int duration;//歌曲时间长度
public String path;//歌曲地址
public long albumId;//图片id
public long id;//歌曲id
public long getAlbumId()
{
return albumId;
}
public void setAlbumId(long albumId)
{
this.albumId = albumId;
}
public long getId()
{
return id;
}
public void setId(long id)
{
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSinger() {
return singer;
}
public void setSinger(String singer) {
this.singer = singer;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
代码中的解释很详细了。
接下来我们要创建一个LocalMusicUtils来获取我们设备本地的音乐。首先通过getContentResolver()获取到contentPervider的cursor对象。
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
然后遍历cursor中的数据
if (cursor != null) {
while (cursor.moveToNext()) {
song = new Song();
name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
}
}
ok,来看一下完整的代码
public class LocalMusicUtils {
//定义一个集合,存放从本地读取到的内容
public static List<Song> list;
public static Song song;
private static String name;
private static String singer;
private static String path;
private static int duration;
private static long size;
private static long albumId;
private static long id;
//获取专辑封面的Uri
private static final Uri albumArtUri = Uri.parse("content://media/external/audio/albumart");
public static List<Song> getmusic(Context context) {
list = new ArrayList<>();
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI
, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor != null) {
while (cursor.moveToNext()) {
song = new Song();
name = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID));
singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
albumId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));
//list.add(song);
//把歌曲名字和歌手切割开
//song.setName(name);
song.setSinger(singer);
song.setPath(path);
song.setDuration(duration);
song.setSize(size);
song.setId(id);
song.setAlbumId(albumId);
if (size > 1000 * 800) {
if (name.contains("-")) {
String[] str = name.split("-");
singer = str[0];
song.setSinger(singer);
name = str[1];
song.setName(name);
} else {
song.setName(name);
}
list.add(song);
}
}
}
cursor.close();
return list;
}
// 转换歌曲时间的格式
public static String formatTime(int time) {
if (time / 1000 % 60 < 10) {
String tt = time / 1000 / 60 + ":0" + time / 1000 % 60;
return tt;
} else {
String tt = time / 1000 / 60 + ":" + time / 1000 % 60;
return tt;
}
}
/**
* 获取专辑封面位图对象
* @param context
* @param song_id
* @param album_id
* @param allowdefalut
* @return
*/
public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefalut, boolean small){
if(album_id < 0) {
if(song_id < 0) {
Bitmap bm = getArtworkFromFile(context, song_id, -1);
if(bm != null) {
return bm;
}
}
if(allowdefalut) {
return getDefaultArtwork(context, small);
}
return null;
}
ContentResolver res = context.getContentResolver();
Uri uri = ContentUris.withAppendedId(albumArtUri, album_id);
if(uri != null) {
InputStream in = null;
try {
in = res.openInputStream(uri);
BitmapFactory.Options options = new BitmapFactory.Options();
//先制定原始大小
options.inSampleSize = 1;
//只进行大小判断
options.inJustDecodeBounds = true;
//调用此方法得到options得到图片的大小
BitmapFactory.decodeStream(in, null, options);
/** 我们的目标是在你N pixel的画面上显示。 所以需要调用computeSampleSize得到图片缩放的比例 **/
/** 这里的target为800是根据默认专辑图片大小决定的,800只是测试数字但是试验后发现完美的结合 **/
if(small){
options.inSampleSize = computeSampleSize(options, 40);
} else{
options.inSampleSize = computeSampleSize(options, 600);
}
// 我们得到了缩放比例,现在开始正式读入Bitmap数据
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
in = res.openInputStream(uri);
return BitmapFactory.decodeStream(in, null, options);
} catch (FileNotFoundException e) {
Bitmap bm = getArtworkFromFile(context, song_id, album_id);
if(bm != null) {
if(bm.getConfig() == null) {
bm = bm.copy(Bitmap.Config.RGB_565, false);
if(bm == null && allowdefalut) {
return getDefaultArtwork(context, small);
}
}
} else if(allowdefalut) {
bm = getDefaultArtwork(context, small);
}
return bm;
} finally {
try {
if(in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 从文件当中获取专辑封面位图
* @param context
* @param songid
* @param albumid
* @return
*/
private static Bitmap getArtworkFromFile(Context context, long songid, long albumid){
Bitmap bm = null;
if(albumid < 0 && songid < 0) {
throw new IllegalArgumentException("Must specify an album or a song id");
}
try {
BitmapFactory.Options options = new BitmapFactory.Options();
FileDescriptor fd = null;
if(albumid < 0){
Uri uri = Uri.parse("content://media/external/audio/media/"
+ songid + "/albumart");
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if(pfd != null) {
fd = pfd.getFileDescriptor();
}
} else {
Uri uri = ContentUris.withAppendedId(albumArtUri, albumid);
ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
if(pfd != null) {
fd = pfd.getFileDescriptor();
}
}
options.inSampleSize = 1;
// 只进行大小判断
options.inJustDecodeBounds = true;
// 调用此方法得到options得到图片大小
BitmapFactory.decodeFileDescriptor(fd, null, options);
// 我们的目标是在800pixel的画面上显示
// 所以需要调用computeSampleSize得到图片缩放的比例
options.inSampleSize = 100;
// 我们得到了缩放的比例,现在开始正式读入Bitmap数据
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
//根据options参数,减少所需要的内存
bm = BitmapFactory.decodeFileDescriptor(fd, null, options);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bm;
}
/**
* 获取默认专辑图片
* @param context
* @return
*/
public static Bitmap getDefaultArtwork(Context context,boolean small) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.RGB_565;
if(small){ //返回小图片
//return
BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.music5), null, opts);
}
//return BitmapFactory.decodeStream(context.getResources().openRawResource(R.drawable.defaultalbum), null, opts);
return null;
}
/**
* 对图片进行合适的缩放
* @param options
* @param target
* @return
*/
public static int computeSampleSize(BitmapFactory.Options options, int target) {
int w = options.outWidth;
int h = options.outHeight;
int candidateW = w / target;
int candidateH = h / target;
int candidate = Math.max(candidateW, candidateH);
if(candidate == 0) {
return 1;
}
if(candidate > 1) {
if((w > target) && (w / candidate) < target) {
candidate -= 1;
}
}
if(candidate > 1) {
if((h > target) && (h / candidate) < target) {
candidate -= 1;
}
}
return candidate;
}
/**
* 根据专辑ID获取专辑封面图
* @param album_id 专辑ID
* @return
*/
public static String getAlbumArt(Context context,long album_id) {
String mUriAlbums = "content://media/external/audio/albums";
String[] projection = new String[]{"album_art"};
Cursor cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Long.toString(album_id)), projection, null, null, null);
String album_art = null;
if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
cur.moveToNext();
album_art = cur.getString(0);
}
cur.close();
String path = null;
if (album_art != null) {
path = album_art;
} else {
//path = "drawable/music_no_icon.png";
//bm = BitmapFactory.decodeResource(getResources(), R.drawable.default_cover);
}
return path;
}
}
ok,这样就把歌曲的信息通过list的方式获取到了,下面的方法是获取专辑图片的fang'f