assets目录下存放的资源文件系统在编译的时候不会编译,不能使用R.XXX.ID的方式来访问。而通过AssetManager类的list方法只能列出文件名,并不能实际获取到文件。想要实现获取歌曲的全部信息包括专辑名、歌手等,可以使用MediaMetadataRetriever类。MediaMetadataRetriever类使用详解
可是在setDataSource时需要传入具体路径,assets目录下传入的路径信息并不能获取到MP3文件,所以只能“曲线救国”了。
下面是具体实现步骤:
- 调用list方法获取assets/music目录下的全部音乐名称;
- 将音乐拷贝到某个具体目录下(newPath);
- 调用MediaMetadataRetriever类的setDataSource方法时传入新的路径;
- 调用MediaMetadataRetriever类的extractMetadata(int keyCode)方法,检索与键值相关联的信息。
好了,大功告成!暂时没想到更好的办法,请求大佬们指导。
private void initView(){
try {
String[] musicFileName=getResources().getAssets().list("music");
if (musicFileName!=null){
for(int i=0;i<musicFileName.length;i++){
//InputStream is=getResources().getAssets().open(musicFileName[i]);
String packageName = getContext().getPackageName();
//定义存放音乐的内存路径
String path="/data/data/"+packageName;
copyMusic(getContext(),musicFileName[i],path+"/"+musicFileName[i]);
File file=new File(path);
File[] subFile=file.listFiles();
getMusicInfo(getContext(),path+"/"+musicFileName[i]);
}
}
}catch (IOException e){
e.printStackTrace();
}
}
/**
* 将assets目录下的音乐复制到指定目录下
*/
private void copyMusic(Context context,String oldPath,String newPath) {
try {
File f=new File(newPath);
if(!f.exists()) {
InputStream is = context.getAssets().open("music/"+oldPath);
FileOutputStream fos = new FileOutputStream(new File(newPath));
byte[] buffer = new byte[1024];
int byteCount=-1;
while((byteCount=is.read(buffer))!=-1) {//循环从输入流读取 buffer字节
fos.write(buffer, 0, byteCount);//将读取的输入流写入到输出流
}
fos.flush();//刷新缓冲区
is.close();
fos.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取歌曲信息
*/
private void getMusicInfo(Context context, String musicFileName) throws IOException {
MediaMetadataRetriever myRetriever = new MediaMetadataRetriever();
myRetriever.setDataSource(musicFileName);
String albumTitle=myRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);//获得音乐专辑的标题
String artist=myRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);//获取音乐的艺术家信息
String title=myRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);//获取音乐标题信息
//创建music对象并赋值
Music music=new Music();
music.title =title;
music.artist=artist;
music.album=albumTitle;
byte[] artwork;
artwork = myRetriever.getEmbeddedPicture();
if (artwork != null) {
Bitmap albumImg = BitmapFactory.decodeByteArray(artwork, 0, artwork.length);
music.albumImg=albumImg;
} else {
music.albumImg= BitmapFactory.decodeResource(context.getResources(), R.drawable.default_music_img);
}
musicList.add(music);
}