MainActivity 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 extract a video by time * and convert it to Bitmap for storage in SDCard ** special note: * getFrameAtTime () the unit of the first parameter of the method is microsecond (us) **/public class MainActivity extends Activity {private Button mButton; @ Overrideprotected 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 {@ Overridepublic 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); // gets the video length (unit: milliseconds) String time = retriever. extractMetadata (MediaMetadataRetriever. METADATA_KEY_DURATION); // gets the video length (in seconds) int seconds = Integer. valueOf (time)/1000; // obtain the bitmap of every second, such as 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:
<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 = "get video frame image" android: layout_centerInParent = "true"/> </RelativeLayout>