Android MediaMetadataRetriever 读取多媒体文件信息,元数据(MetaData)

时间:2021-09-13 01:32:30

音乐播放器通常需要获取歌曲的专辑、作者、标题、年代等信息,将这些信息显示到UI界面上。

1、一种方式:解析媒体文件  

命名空间:android.media.MediaMetadataRetriever

android提供统一的接口MediaMetadataRetriever解析媒体文件、获取媒体文件中取得帧和元数据(视频/音频包含的标题、格式、艺术家等信息)。

1   MediaMetadataRetriever mmr = new MediaMetadataRetriever();
2 String str = getExternalStorageDirectory() + "music/hetangyuese.mp3"; 3 mmr.setDataSource(str);
4 // api level 10, 即从GB2.3.3开始有此功能
5 String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
6 // 专辑名
7 String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
8 // 媒体格式
9 String mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
10 // 艺术家
11 String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
12 // 播放时长单位为毫秒
13 String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
14 // 从api level 14才有,即从ICS4.0才有此功能
15 String bitrate = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE);
16 // 路径
17 String date = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);

(1)关于视频缩略图:

2.2 之后:因为用了ThumbnailUtils类:

 Bitmap  b = ThumbnailUtils.createVideoThumbnail(path,Video.Thumbnails.MICRO_KIND);
ImageView iv = new ImageView(this);

2.2 之前:

使用MediaMetadataRetriever这个类;还可以通过getFrameAtTime方法取得指定time位置的Bitmap,即可以实现抓图(包括缩略图)功能

但是 里面有个问题 
1.0之后 这个类被隐藏了 貌似2.3之后这个类又出现了,但是还可以直接copy源码进去使用:http://blog.csdn.net/lostinai/article/details/7734699 (教程)

  // 对于视频,取第一帧作为缩略图,也就是怎样从filePath得到一个Bitmap对象。
private Bitmap createVideoThumbnail(String filePath) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
retriever.setDataSource(filePath);
bitmap = retriever.captureFrame();
} catch(IllegalArgumentException ex) {
// Assume this is a corrupt video file
} catch (RuntimeException ex) {
// Assume this is a corrupt video file.
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
return bitmap;
}

(2)关于音乐缩略图:

  // 对于音乐,取得AlbumImage作为缩略图,还是用MediaMetadataRetriever
private Bitmap createAlbumThumbnail(String filePath) {
Bitmap bitmap = null;
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setMode(MediaMetadataRetriever.MODE_GET_METADATA_ONLY);
retriever.setDataSource(filePath);
byte[] art = retriever.extractAlbumArt();
bitmap = BitmapFactory.decodeByteArray(art, 0, art.length);
} catch(IllegalArgumentException ex) {
} catch (RuntimeException ex) {
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
// Ignore failures while cleaning up.
}
}
return bitmap;
}

注意:直接得到Bitmap对象,把图片缩小到合适大小就OK。

这样获取出来的,信息有时候可能有乱码:

1、Java如何获取文件编码格式  (使用第三方库进行处理)

2、自己判断字符串是否有乱码,然后自行处理。

 private boolean isMessyCode(String strName) {
try {
Pattern p = Pattern.compile("\\s*|\t*|\r*|\n*");
Matcher m = p.matcher(strName);
String after = m.replaceAll("");
String temp = after.replaceAll("\\p{P}", "");
char[] ch = temp.trim().toCharArray(); int length = (ch != null) ? ch.length : 0;
for (int i = 0; i < length; i++) {
char c = ch[i];
if (!Character.isLetterOrDigit(c)) {
String str = "" + ch[i];
if (!str.matches("[\u4e00-\u9fa5]+")) {
return true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
} return false;
}

检查字符串是否乱码,乱码情况下要做相应的处理

2、二种方式:读取媒体文件数据库(避免乱码)

创建java bean:

 public class MediaInfo {
private int playDuration = 0;
private String mediaName = "";
private String mediaAlbum = "";
private String mediaArtist = "";
private String mediaYear = "";
private String mFileName = "";
private String mFileType = "";
private String mFileSize = "";
private String mFilePath = ""; public Bitmap getmBitmap() {
return mBitmap;
} public void setmBitmap(Bitmap mBitmap) {
this.mBitmap = mBitmap;
} private Bitmap mBitmap = null; public String getMediaName() {
return mediaName;
} public void setMediaName(String mediaName) {
try {
mediaName =new String (mediaName.getBytes("ISO-8859-1"),"GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.mediaName = mediaName;
} public String getMediaAlbum() {
return mediaAlbum;
} public void setMediaAlbum(String mediaAlbum) {
try {
mediaAlbum =new String (mediaAlbum.getBytes("ISO-8859-1"),"GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.mediaAlbum = mediaAlbum;
} public String getMediaArtist() {
return mediaArtist;
} public void setMediaArtist(String mediaArtist) {
try {
mediaArtist =new String (mediaArtist.getBytes("ISO-8859-1"),"GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.mediaArtist = mediaArtist;
}
}

媒体信息bean

操作类:

 public class MediaInfoProvider {  

         /**
* context
*/
private Context mContext = null; /**
* data path
*/
private static final String dataPath = "/mnt"; /**
* query column
*/
private static final String[] mCursorCols = new String[] {
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.MIME_TYPE,
MediaStore.Audio.Media.SIZE, MediaStore.Audio.Media.DATA }; /**
* MediaInfoProvider
* @param context
*/
public MediaInfoProvider(Context context) {
this.mContext = context;
} /**
* get the media file info by path
* @param filePath
* @return
*/
public MediaInfo getMediaInfo(String filePath) { /* check a exit file */
File file = new File(filePath);
if (file.exists()) {
Toast.makeText(mContext, "sorry, the file is not exit!",
Toast.LENGTH_SHORT);
} /* create the query URI, where, selectionArgs */
Uri Media_URI = null;
String where = null;
String selectionArgs[] = null; if (filePath.startsWith("content://media/")) {
/* content type path */
Media_URI = Uri.parse(filePath);
where = null;
selectionArgs = null;
} else {
/* external file path */
if(filePath.indexOf(dataPath) < 0) {
filePath = dataPath + filePath;
}
Media_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
where = MediaColumns.DATA + "=?";
selectionArgs = new String[] { filePath };
} /* 查询 */
Cursor cursor = mContext.getContentResolver().query(Media_URI,
mCursorCols, where, selectionArgs, null);
if (cursor == null || cursor.getCount() == 0) {
return null;
} else {
cursor.moveToFirst();
MediaInfo info = getInfoFromCursor(cursor);
printInfo(info);
return info;
}
} /**
* 获取媒体信息
* @param cursor
* @return
*/
private MediaInfo getInfoFromCursor(Cursor cursor) {
MediaInfo info = new MediaInfo(); /* file name */
if(cursor.getString(1) != null) {
info.setmFileName(cursor.getString(1));
}
/* media name */
if(cursor.getString(2) != null) {
info.setMediaName(cursor.getString(2));
}
/* play duration */
if(cursor.getString(3) != null) {
info.setPlayDuration(cursor.getInt(3));
}
/* artist */
if(cursor.getString(4) != null) {
info.setMediaArtist(cursor.getString(4));
}
/* album */
if(cursor.getString(5) != null) {
info.setMediaAlbum(cursor.getString(5));
}
/* media year */
if (cursor.getString(6) != null) {
info.setMediaYear(cursor.getString(6));
} else {
info.setMediaYear("undefine");
}
/* media type */
if(cursor.getString(7) != null) {
info.setmFileType(cursor.getString(7).trim());
}
/* media size */
if (cursor.getString(8) != null) {
float temp = cursor.getInt(8) / 1024f / 1024f;
String sizeStr = (temp + "").substring(0, 4);
info.setmFileSize(sizeStr + "M");
} else {
info.setmFileSize("undefine");
}
/* media file path */
if (cursor.getString(9) != null) {
info.setmFilePath(cursor.getString(9));
} return info;
}
}