android捕获视频帧 [英] android capture video frame
问题描述
我需要获取视频文件的一帧(它可能在 sdcard、缓存目录或应用程序目录中).我的应用程序中有 android.media 包,里面有 MediaMetadataRetriever 类.要将第一帧转换为位图,我使用代码:
I need to get a frame of a video file (it may be on sdcard, cache dir or app dir). I have package android.media in my application and inside I have class MediaMetadataRetriever. To get first frame into a bitmap, I use code:
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 播放视频)
But this it's not working. It throws an exception (java.lang.RuntimeException: setDataSource failed: status = 0x80000000) when I set data source. Do you know how to make this code to work? Or Do you have any similar (simple) solution without using ffmpeg or other external libraries? videoUri is a valid uri (media player can play video from that 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;
}
如果您使用路径而不是文件描述符也可以使用.
Also works if you use a path instead of a filedescriptor.
这篇关于android捕获视频帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!