我需要获取视频文件的帧(它可能在 sdcard、缓存目录或应用程序目录中)。我的应用程序中有 android.media 包,里面有 MediaMetadataRetriever 类。要将第一帧放入位图中,我使用代码:
public static Bitmap getVideoFrame(Context context, Uri videoUri) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
retriever.setDataSource(context, videoUri);
return retriever.captureFrame();
} catch (IllegalArgumentException ex) {
throw new RuntimeException();
} catch (RuntimeException ex) {
throw new RuntimeException();
} finally {
retriever.release();
}
}
但这行不通。当我设置数据源时,它抛出一个异常(java.lang.RuntimeException:setDataSource failed:status = 0x80000000)。你知道如何使这段代码工作吗?或者您是否有任何类似(简单)的解决方案而不使用 ffmpeg 或其他外部库? videoUri 是一个有效的 uri(媒体播放器可以播放来自该 URI 的视频)
最佳答案
以下对我有用:
public static Bitmap getVideoFrame(FileDescriptor FD) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
try {
retriever.setDataSource(FD);
return retriever.getFrameAtTime();
} catch (IllegalArgumentException ex) {
ex.printStackTrace();
} catch (RuntimeException ex) {
ex.printStackTrace();
} finally {
try {
retriever.release();
} catch (RuntimeException ex) {
}
}
return null;
}
如果您使用路径而不是文件描述符,也适用。
关于android捕获视频帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5337505/