Android中获取视频的第一帧图片或者最后一帧图片

核心类

MediaMetadataRetriever

Google文档说明:

https://developer.android.google.cn/reference/android/media/MediaMetadataRetriever

mediametadataretriever类提供了从输入媒体文件检索帧和源数据的统一接口

1 获取网络视频的第一帧或者最后一帧

此处我用的是Glide4.7版本去获取网络视频的某一帧,若你使用的是其他网络库如Fresco可以参考(https://www.jianshu.com/p/cd3996b5c155)

MediaMetadataRetriever设置的常量包含很多种类,按需配置就好:

/**
 * This option is used with {@link #getFrameAtTime(long, int)} to retrieve
 * a sync (or key) frame associated with a data source that is located
 * right before or at the given time.
 *
 * @see #getFrameAtTime(long, int)
 */
OPTION_PREVIOUS_SYNC,
/**
 * This option is used with {@link #getFrameAtTime(long, int)} to retrieve
 * a sync (or key) frame associated with a data source that is located
 * right after or at the given time.
 *
 * @see #getFrameAtTime(long, int)
 */
OPTION_NEXT_SYNC,
/**
 * This option is used with {@link #getFrameAtTime(long, int)} to retrieve
 * a sync (or key) frame associated with a data source that is located
 * closest to (in time) or at the given time.
 *
 * @see #getFrameAtTime(long, int)
 */
OPTION_CLOSEST_SYNC,
/**
 * This option is used with {@link #getFrameAtTime(long, int)} to retrieve
 * a frame (not necessarily a key frame) associated with a data source that
 * is located closest to or at the given time.
 *
 * @see #getFrameAtTime(long, int)
 */
OPTION_CLOSEST
具体代码如下:
RequestOptions requestOptions = new RequestOptions();
requestOptions.set(FRAME_OPTION,MediaMetadataRetriever.OPTION_NEXT_SYNC);
//此处我用的是饺子播放器,设置饺子播放器的视频封面mMyJZVideoPlayerStandard.thumbImageView
GlideApp.with(this).load(player_uri).apply(requestOptions).into(mMyJZVideoPlayerStandard.thumbImageView);

2 获取本地视频的第一帧或者最后一帧

MediaMetadataRetriever media = new MediaMetadataRetriever();
media.setDataSource( localVideoEntity.path );
// 视频封面
Bitmap videoCoverBitmap = media.getFrameAtTime();
localVideoEntity.bitmapPath = saveVideoBitmap( videoCoverBitmap );//此处我将bitmap转换成了Path路径
private String saveVideoBitmap( Bitmap bitmap ) {
    File file = new File( getCacheDir() + File.separator + UUID.randomUUID() + ".jpg" );
    try {
        if( !file.getParentFile().exists() ) file.mkdirs();
        FileOutputStream out = new FileOutputStream(file);
        if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out)) {
            out.flush();
            out.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file.getAbsolutePath();
}

具体还有很多获取其他多媒体文件(音乐,相册,视频等等)数据元的方式可以参考文档

或者其他大佬写的博客:

https://www.cnblogs.com/CharlesGrant/p/5800250.html

具体的第三方开源方案:

https://github.com/dengyuhan/MediaMetadataRetrieverCompat

视频播放器的地址:

https://github.com/lipangit/JiaoZiVideoPlayer/wiki

猜你喜欢

转载自blog.csdn.net/yang1349day/article/details/81486933