get duration of audio file

后端 未结 10 1165
生来不讨喜
生来不讨喜 2020-12-07 19:15

I have made a voice recorder app, and I want to show the duration of the recordings in a listview. I save the recordings like this:

MediaRecorder recorder =          


        
10条回答
  •  生来不讨喜
    2020-12-07 19:37

    The quickest way to do is via MediaMetadataRetriever. However, there is a catch

    if you use URI and context to set data source you might encounter bug https://code.google.com/p/android/issues/detail?id=35794

    Solution is use absolute path of file to retrieve metadata of media file.

    Below is the code snippet to do so

     private static String getDuration(File file) {
                    MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
                    mediaMetadataRetriever.setDataSource(file.getAbsolutePath());
                    String durationStr = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
                    return Utils.formateMilliSeccond(Long.parseLong(durationStr));
                }
    

    Now you can convert millisecond to human readable format using either of below formats

         /**
             * Function to convert milliseconds time to
             * Timer Format
             * Hours:Minutes:Seconds
             */
            public static String formateMilliSeccond(long milliseconds) {
                String finalTimerString = "";
                String secondsString = "";
    
                // Convert total duration into time
                int hours = (int) (milliseconds / (1000 * 60 * 60));
                int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
                int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
    
                // Add hours if there
                if (hours > 0) {
                    finalTimerString = hours + ":";
                }
    
                // Prepending 0 to seconds if it is one digit
                if (seconds < 10) {
                    secondsString = "0" + seconds;
                } else {
                    secondsString = "" + seconds;
                }
    
                finalTimerString = finalTimerString + minutes + ":" + secondsString;
    
        //      return  String.format("%02d Min, %02d Sec",
        //                TimeUnit.MILLISECONDS.toMinutes(milliseconds),
        //                TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
        //                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds)));
    
                // return timer string
                return finalTimerString;
            }
    

提交回复
热议问题