MainActivity is as follows:
Copy codeThe Code is as follows: package cn. testmediametadataretriever;
Import java. io. File;
Import java. io. FileOutputStream;
Import android. media. MediaMetadataRetriever;
Import android. OS. Bundle;
Import android. OS. Environment;
Import android. app. Activity;
Import android. graphics. Bitmap;
Import android. graphics. Bitmap. CompressFormat;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
/**
* Demo description:
* Use MediaMetadataRetriever to capture videos by Time
* Convert to Bitmap and store it in SDCard
*
* Special Note:
* The unit of the first parameter of the getFrameAtTime () method is microsecond (us)
*
*/
Public class MainActivity extends Activity {
Private Button mButton;
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Init ();
}
Private void init (){
MButton = (Button) findViewById (R. id. button );
MButton. setOnClickListener (new ClickListenerImpl ());
}
Private class ClickListenerImpl implements OnClickListener {
@ Override
Public void onClick (View v ){
Switch (v. getId ()){
Case R. id. button:
GetBitmapsFromVideo ();
Default:
Break;
}
}
}
Public void getBitmapsFromVideo (){
String dataPath = Environment. getExternalStorageDirectory () + "/testVideo.mp4 ";
MediaMetadataRetriever retriever = new MediaMetadataRetriever ();
Retriever. setDataSource (dataPath );
// Obtain the video length (unit: milliseconds)
String time = retriever. extractMetadata (MediaMetadataRetriever. METADATA_KEY_DURATION );
// Obtain the video length (in seconds)
Int seconds = Integer. valueOf (time)/1000;
// Obtain the bitmap of every second, for example, the first second and the second.
For (int I = 1; I <= seconds; I ++ ){
Bitmap bitmap = retriever. getFrameAtTime (I * 1000*1000, MediaMetadataRetriever. OPTION_CLOSEST_SYNC );
String path = Environment. getExternalStorageDirectory () + File. separator + I + ". jpg ";
FileOutputStream fos = null;
Try {
Fos = new FileOutputStream (path );
Bitmap. compress (CompressFormat. JPEG, 80, fos );
Fos. close ();
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
}
Main. xml is as follows:Copy codeThe Code is as follows: <RelativeLayout
Xmlns: android = "http://schemas.android.com/apk/res/android"
Xmlns: tools = "http://schemas.android.com/tools"
Android: layout_width = "match_parent"
Android: layout_height = "match_parent"
>
<Button
Android: id = "@ + id/button"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "getting video frame images"
Android: layout_centerInParent = "true"
/>
</RelativeLayout>