Android获取视频预览图(或首帧)和获取时长需要用到MediaMetadataRetriever类,获取预览图使用getFrameAtTime()方法,获取时长使用extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)方法,示例代码如下:
ImageView iv = findViewById(R.id.imageView);
TextView tv = findViewById(R.id.textView);
String fileName = "a.mp4";
try {
// 获取预览图
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
AssetFileDescriptor afd = getAssets().openFd(fileName);
// mmr.setDataSource(afd.getFileDescriptor()); // failed
mmr.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
Bitmap previewBitmap = mmr.getFrameAtTime();
// 缩放
int PREVIEW_VIDEO_IMAGE_HEIGHT = 300; // Pixels
int videoWidth = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));
int videoHeight = Integer.parseInt(mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT));
int videoViewWidth = PREVIEW_VIDEO_IMAGE_HEIGHT * videoWidth / videoHeight;
int videoViewHeight = PREVIEW_VIDEO_IMAGE_HEIGHT;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(previewBitmap, videoViewWidth, videoViewHeight, true);
iv.setImageBitmap(scaledBitmap);
// 获取时长
String strDuration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
int duration = Integer.parseInt(strDuration) / 1000;
tv.setText(String.format("%d:%02d", duration / 60, duration % 60));
mmr.release();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
注意
1. getFrameAtTime方法获取的是视频中具有代表性的一帧,并不是首帧,原注释是“This method finds a representative frame at any time position if possible, and returns it as a bitmap.”,获取首帧需要使用getFrameAtTime(0)。
2. 使用setDataSource方法时,如果只传递FileDescriptor一个参数运行时会报错,必须传递三个参数。
3. 代码中的a.mp4文件在assets目录中(Android Studio添加assets目录方法:在模块名字上右键 | New | Folder | Assets Folder)。