Android系统为了一些常用的信息(如音乐、视频、图像、联系人等)内置了一系列的ContentProvider,所以我们可以通过这个来获取Anroid中本地音乐,首先得加入权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
如果想要修改甚至删除数据,还要加上写的权限
为了实例化mp3音乐,我们首先定义一个mp3info的bean,里面给出所需要的属性,比如id,title,album等等,另外为了使其能在activity与service中进行通信传值,需要序列化,android中序列化一般使用Parcelable,用法可以参考 点击打开链接
mp3info.java
public class Mp3Info implements Parcelable{
private long id;
private String title;
private String artist;
private String album;
private long albumId;
private long duration;
private long size;
private String url;
public Mp3Info(){
}
public Mp3Info(Parcel parcel){
id = parcel.readLong();
title = parcel.readString();
artist = parcel.readString();
album = parcel.readString();
albumId = parcel.readLong();
duration = parcel.readLong();
size = parcel.readLong();
url = parcel.readString();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public long getAlbumId() {
return albumId;
}
public void setAlbumId(long albumId) {
this.albumId = albumId;
}
public long getDuration() {
return duration;
}
public void setDuration(long duration) {
this.duration = duration;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeString(title);
dest.writeString(artist);
dest.writeString(album);
dest.writeLong(albumId);
dest.writeLong(duration);
dest.writeLong(size);
dest.writeString(url);
}
public static final Parcelable.Creator<Mp3Info> CREATOR = new Creator<Mp3Info>() {
@Override
public Mp3Info[] newArray(int size) {
return new Mp3Info[size];
}
@Override
public Mp3Info createFromParcel(Parcel source) {
return new Mp3Info(source);
}
};
}
获取本地音乐及其专辑图片的代码,部分参考他人代码, MediaUtil.java
// 获取专辑封面的Uri
private static final Uri albumArtUri = Uri
.parse("content://media/external/audio/albumart");
/**
* 用于从数据库中查询歌曲的信息,保存在List当中
*
* @return
*/
public static List<Mp3Info> getMp3Infos(Context context) {
Cursor cursor = context.getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
MediaStore.Audio.Media .DEFAULT_SORT_ORDER);
List<Mp3Info> mp3Infos = new ArrayList<Mp3Info>();
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
Mp3Info mp3Info = new Mp3Info();
long id = cursor.getLong(cursor
.getColumnIndex(MediaStore.Audio.Media._ID)); // 音乐id
String title = cursor.getString((cursor
.getColumnIndex(MediaStore.Audio.Media.TITLE))); // 音乐标题
String artist = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST)); // 艺术家
String album = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM)); // 专辑
long albumId = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
long duration = cursor.getLong(cursor
.getColumnIndex(MediaStore.Audio.Media.DURATION)); // 时长
long size = cursor.getLong(cursor
.getColumnIndex(MediaStore.Audio.Media.SIZE)); // 文件大小
String url = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA)); // 文件路径
int isMusic = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.IS_MUSIC)); // 是否为音乐
if (isMusic != 0) { // 只把音乐添加到集合当中
mp3Info.setId(id);
mp3Info.setTitle(title);
mp3Info.setArtist(artist);
mp3Info.setAlbum(album);
mp3Info.setAlbumId(albumId);
mp3Info.setDuration(duration);
mp3Info.setSize(size);
mp3Info.setUrl(url);
mp3Infos.add(mp3Info);
}
}
cursor.close();
return mp3Infos;
}
/**
* 格式化时间,将毫秒转换为分:秒格式
*
* @param time
* @return
*/
public static String formatTime(long time) {
String min = time / (1000 * 60) + "";
String sec = time % (1000 * 60) + "";
if (min.length() < 2) {
min = "0" + time / (1000 * 60) + "";
} else {
min = time / (1000 * 60) + "";
}
if (sec.length() == 4) {
sec = "0" + (time % (1000 * 60)) + "";
} else if (sec.length() == 3) {
sec = "00" + (time % (1000 * 60)) + "";
} else if (sec.length() == 2) {
sec = "000" + (time % (1000 * 60)) + "";
} else if (sec.length() == 1) {
sec = "0000" + (time % (1000 * 60)) + "";
}
return min + ":" + sec.trim().substring(0, 2);
}
/**
* 获取默认专辑图片
*
* @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.default_cover_64), null, opts);
}
return BitmapFactory.decodeStream(context.getResources()
.openRawResource(R.drawable.default_cover_640), null, opts);
}
/**
* 从文件当中获取专辑封面位图
*
* @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
* @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 options
* @param target
* @return
*/
public static int computeSampleSize(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;
}