Mainactivity is as follows:
Copy Code code 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 intercept video in time
* and converted to bitmap for storage in SDcard
*
* Special attention:
* Getframeattime () method The unit of the first parameter 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);
Gets the length of the video (in milliseconds)
String time = Retriever.extractmetadata (mediametadataretriever.metadata_key_duration);
Gets the length of the video (in seconds)
int seconds = integer.valueof (time)/1000;
To get the bitmap of every second moment, like the first second, 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, FOS);
Fos.close ();
catch (Exception e) {
E.printstacktrace ();
}
}
}
}
Main.xml is as follows:
Copy Code code 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 frame picture of video"
Android:layout_centerinparent= "true"
/>
</RelativeLayout>