在安卓中获取视频的长度



我想从我的设备获取保存视频的长度。我尝试过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);
        }
    }
}

试试这个

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();

这对我有用。

试试这个:

    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();
        }
    });

相关内容

  • 没有找到相关文章

最新更新