get video duration from URL in android app

后端 未结 2 1133
长发绾君心
长发绾君心 2021-01-13 10:02

I\'m working on an app where the user can see all the video\'s information and title that are stored on a SERVER. I\'m almost done with it except that no matter how I code i

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 10:31

    This is working for me , (Use this code in background thread if your app is getting slow)

    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
      retriever.setDataSource("YourVideofileUrl", new HashMap());
      String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
      long timeInMillisec = Long.parseLong(time);
      retriever.release();
      String duration=convertMillieToHMmSs(timeInMillisec); //use this duration
    

    and

     public static String convertMillieToHMmSs(long millie) {
        long seconds = (millie / 1000);
        long second = seconds % 60;
        long minute = (seconds / 60) % 60;
        long hour = (seconds / (60 * 60)) % 24;
    
        String result = "";
        if (hour > 0) {
            return String.format("%02d:%02d:%02d", hour, minute, second);
        }
        else {
            return String.format("%02d:%02d" , minute, second);
        }
    
    }
    

    Do in background using AsyncTask or coroutines if its slow

     AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                retriever.setDataSource(model.getLink(), new HashMap());
                String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                long timeInMillisec = Long.parseLong(time);
                retriever.release();
                String durations=convertMillieToHMmSs(timeInMillisec); //use this duration
                Log.d("durationns",durations);
    
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        duration.setText(durations);//set in textview
                    }
                });
            }
        });
    

提交回复
热议问题