1

我想从我的设备获取已保存视频的长度。我试过了,MediaMetadataRetriever但我的应用程序崩溃了。我正在 Android 6.0 上对其进行测试,但它根本不起作用。

下面是我的活动。

    public class MainActivity extends AppCompatActivity {

    private static final int PICK_IMAGE_REQUEST = 1; // put it on the top.
    private Button btnOpenGallery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        btnOpenGallery = (Button)findViewById(R.id.btnOpenGallery);
        btnOpenGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent();
                intent.setType("video/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            Uri selectedImageUri = data.getData();
            String strPath = selectedImageUri.getPath();
            Log.e("Path is ","===>"+strPath);


            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(strPath); // Enter Full File Path Here
            String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long timeInmillisec = Long.parseLong(time);
            Log.e("Media duration in ","==>"+timeInmillisec);

        }
    }
}
4

2 回答 2

1

试试这个

MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
int duration = mp.getDuration();
mp.release();

这对我有用。

于 2017-03-30T11:41:00.167 回答
0

尝试这个:

    MediaPlayer mp = MediaPlayer.create(getActivity(), Uri.parse(Environment.getExternalStorageDirectory() + "/Downloads/" + "vid" + ".mp4")); // Downloads is the folder and vid is video file.
    mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            int duration = mp.getDuration();
            mp.release();
        }
    });
于 2017-03-30T12:25:02.480 回答